如何获取functions.php中的当前帖子类型以便全局使用?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何获取functions.php中的当前帖子类型以便全局使用?相关的知识,希望对你有一定的参考价值。

我想检查任何页面或帖子的帖子类型,并根据帖子类型显示一些功能。所以我在functions.php中使用了一个函数,它在管理页面中使用时返回帖子类型,但在主题页面上没有。

如果帖子类型是page,我需要这个函数来包含一个php文件。所以它必须在系统范围内工作(如果可能的话)。在模板,管理,编辑和发布页面。

这是我正在使用的功能:

function vart_current_post_type() {
    global $post, $typenow, $current_screen;

    if ( $post && $post->post_type ) {
        return $post->post_type;
    }

    elseif ( isset( $_GET[ 'post' ] ) ) {
        return get_post_type( $_GET[ 'post' ] );
    }

    elseif ( $typenow ) {
        return $typenow;
    }

    elseif ( $current_screen && $current_screen->post_type ) {
        return $current_screen->post_type;
    }

    elseif ( isset( $_REQUEST[ 'post_type' ] ) ) {
        return sanitize_key( $_REQUEST[ 'post_type' ] );
    }

    return null;
}

add_action( 'init', 'vart_current_post_type' );

请告诉我,为了使其适用于主题模板和页面,我该怎么做?

谢谢。

答案

有一种本地方法可以找出当前的帖子类型:https://developer.wordpress.org/reference/functions/get_post_type/

$post_type = get_post_type();
另一答案

init钩子上,$post对象尚未填充。

请参阅this以了解WP钩子(动作)执行情况。如您所见,在init之后很快就会选择帖子。更确切地说,甚至在init hook之后解析请求。所以在初始化动作中没有简单的方法来获取帖子类型,我担心。

使用wp钩子,您可以使用您的功能获得帖子类型。

以上是关于如何获取functions.php中的当前帖子类型以便全局使用?的主要内容,如果未能解决你的问题,请参考以下文章