在 wordpress 的主题 functions.php 中获取全局 $post

Fetch global $post inside theme functions.php of wordpress

我正在使用 wordpress。

themes/my_theme/functions.php 中,我想执行如下操作:

global $post;
$is_mobile = get_post_meta($post->ID, 'mobile')[0];

然后我发现 global $post 是空的。

我试过了:

function mobile_actions() {
    global $post;
    var_dump($post);
}
add_action('wp_head', 'mobile_actions');

没关系。

并且:

function mobile_actions() {
    global $post;
    var_dump($post);
}
add_action('wp_loaded', 'mobile_actions');

运气不好。

那么,如果我想获取那个 global $post,我应该最早使用哪个钩子?

最早你可以在 'wp' hook. This hook runs the register_globals() 函数中执行此操作,它公开了 $post.

不过,'wp_head' 也足够了。