【问题标题】:How does one determine which page is currently being edited using WordPress inbuilt functionality?使用 WordPress 内置功能如何确定当前正在编辑哪个页面?
【发布时间】:2021-04-27 19:02:44
【问题描述】:

我在我的 WordPress 主题中编写了一个模块,它过于复杂且无关紧要。

我需要包含一段代码,并且需要一种可靠的方法来确定用户当前是否正在编辑特定页面。

本质上,我想要前端检查的等价物:

if (is_front_page()) {

但是,在编辑器页面上时。

还需要能够定位没有特殊名称的页面,例如首页/商店页面。所以我可能需要按帖子 ID 定位。

执行此检查的最简洁方法是什么?

我已经尝试了上面的功能,以及:

$screen = get_current_screen();

但是,这会导致严重错误:

Fatal error: Uncaught Error: Call to undefined function get_current_screen() in ... points to line.

还尝试了其他几种方法,我只记下一些。我以为我可以让一个人工作,但似乎没有人能做到这一点。请有人指出我正确的方向吗?

编辑 添加示例 sn -p


// This creates the fatal error.
// $screen = get_current_screen();
// var_dump($screen);

// This is for the front-end 
// if (is_front_page()) {

// global $pagenow;
// var_dump($pagenow);
// if ($pagenow == 'post.php') {
// This returns string(8) "post.php" which is not descript enough.

// This is front-end
// global $post;
// $post_id = $post->ID;
// Post ID 3887 is Home

if ($post_id == '3887') {

    echo 'hello!';

    require_once('inc/overlays/page-template/fc-front-page.php');
    
} else {

    echo 'Well that did not work!';

}

我这样做的原因无关紧要,我只是想在不同的文件夹中包含一个文件,调用的文件将根据当前正在编辑的页面而有所不同!

【问题讨论】:

  • 您到底看到了什么严重错误?
  • @cabrerahector - 为您更新了问题:)
  • 啊,我认为您通常无法从您的主题中访问管理功能,例如 get_current_screen(),除非您在主题中使用特定的挂钩,例如 admin_init
  • 话虽如此,如果您希望我们提供比这更多的帮助,请分享Minimal, Reproducible Example(并解释您为什么这样做),以便我们分享更多建议。跨度>
  • 为您添加了该信息 :) 我喜欢 admin_init,但我仍然需要了解如何确定当前正在编辑哪个页面。

标签: php wordpress function wordpress-theming


【解决方案1】:

get_current_screen() 仅在管理页面上有效。

WP_Screen 对象通过current_screen 操作钩子在admin_init 操作钩子之后设置。触发钩子序列可以参考Plugin API/Action Reference and the Actions Run During a Typical Request

要确保WP_Screen 对象正在触发,您可以使用以下函数。它将屏幕对象作为 html 注释输出到支持它的管理页面上。

add_action( 'current_screen', 'print_r_get_current_screen' );

if ( ! function_exists( 'print_r_get_current_screen' ) ) {

    function print_r_get_current_screen() {

        echo PHP_EOL . '<!--' . PHP_EOL;
        print_r( get_current_screen() );
        echo PHP_EOL . '-->' . PHP_EOL;

    };

};

但我认为使用当前屏幕不会帮助您实现您想要做的事情。

您可以使用get_option( 'page_on_front' );获取首页的id。

add_action( 'init', 'print_r_get_option_page_on_front' );

if ( ! function_exists( 'print_r_get_option_page_on_front' ) ) {

    function print_r_get_option_page_on_front() {

        echo PHP_EOL . '<!--' . PHP_EOL;
        print_r( get_option( 'page_on_front' ) ); //... 0 if undefined, page ID if defined
        echo PHP_EOL . '-->' . PHP_EOL;

    };

};

对于 woocommerce,我很确定您可以使用 woocommerce_get_page_id( 'shop' )

【讨论】:

  • 欣赏兴趣。不过我不能用这些,除非你能告诉我怎么用!
猜你喜欢
  • 1970-01-01
  • 2015-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-26
  • 1970-01-01
  • 2020-05-12
  • 1970-01-01
相关资源
最近更新 更多