在wordpress中的function.php中没有获取当前帖子ID

Jit*_*mor 0 wordpress

由于某种原因,我想在function.php文件中获取当前的post id.

我使用了以下代码:

<?php 
global $wp_query;
$postid = $wp_query->post->ID;
echo $postid;
?> 
Run Code Online (Sandbox Code Playgroud)

但没有得到任何东西......

rne*_*ius 5

functions.php运行时,您无法使用帖子ID .你需要挂钩'template_redirect'(或稍后):

function get_current_post_ID() {
    $postid = get_queried_object_id();
}
add_action( 'template_redirect', 'get_current_post_ID' );
Run Code Online (Sandbox Code Playgroud)