WordPress插件开发中如何检测当前页面

How to detect current page in WordPress plugin development

我目前正在开发一个插件,我将限制某些页面仅供登录用户访问。我指的是我们在 Wordpress 中创建的普通页面。

我在网上找到了这个,但它似乎对我不起作用。

function check_the_current_page(){
    echo $slug = basename(get_permalink());
}

add_action( "init", "check_the_current_page" ); 

我的另一个选择是检测当前页面 ID,如下面的代码所示。屏幕上没有打印任何内容,可能是我使用了错误的钩子之类的,有人帮助我

function check_the_current_page(){
    global $post;
    echo "Post id: ".$post->ID;
}

add_action( "init", "check_the_current_page" );

如果我能够在上述情况之一中获得输出,那将非常简单,但现在两种情况都没有在屏幕上打印任何内容

Try This Code Work For Me global $post dosent work in init

function check_the_current_page() {
    global $post;
    echo "Post id: " . $post->ID;
}

add_action( "wp", "check_the_current_page" );