admin管理员组

文章数量:1122846

I am trying to get the post id outside the loop in functions.php.but what error i am getting : Notice: Trying to get property of non-object in functions.php on line 549

function theme_myeffecto_disable() {
  global $wp_query;
  $post_id = $wp_query->post->ID;

  $showreaction = get_post_meta( $post_id, 'post_reaction_show', true );
  $showreaction = isset($showreaction) ? $showreaction : true;
  var_dump($showreaction);
}
add_action( 'init', 'theme_myeffecto_disable', 20 );

and $showrating always comes false weather it is true or false :(

I am trying to get the post id outside the loop in functions.php.but what error i am getting : Notice: Trying to get property of non-object in functions.php on line 549

function theme_myeffecto_disable() {
  global $wp_query;
  $post_id = $wp_query->post->ID;

  $showreaction = get_post_meta( $post_id, 'post_reaction_show', true );
  $showreaction = isset($showreaction) ? $showreaction : true;
  var_dump($showreaction);
}
add_action( 'init', 'theme_myeffecto_disable', 20 );

and $showrating always comes false weather it is true or false :(

Share Improve this question asked Sep 12, 2017 at 14:45 hamidablehamidable 11 bronze badge 2
  • Are you trying to get the id of the post when on a single post view only? – Jacob Peattie Commented Sep 12, 2017 at 14:48
  • 1 The query hasn't run yet on the init action, it's too early. – Milo Commented Sep 12, 2017 at 15:33
Add a comment  | 

3 Answers 3

Reset to default 0

You can not get post ID in init hook. The first safe hook to get post id is template_redirect.

See this answer for more details:

you could simply just add this in your template

<?php
 global $post;

if($post >= 1) {
echo $post->ID;
}
?>

or if you want it in your functions.php and use it any where

function get_my_post_id() {

  global $post;

   if($post >= 1) {
    echo $post->ID;
}
}

add_shortcode( 'post_id', 'get_my_post_id' );

// then add the shortcode in your template file where you want the post_id output
<?php echo do_shortcode('[post_id]'); ?> 

Rizwan Mention before you can't use init hook for this. The first hook that is safe to get post id is template_redirect. Here you can see details. I've used get_queried_object_id() to get current post id.

add_action('template_redirect', function () {
    $post_id = get_queried_object_id();
    // if post id available, this will not execute in archive pages.
    if ($post_id) {
        $showreaction = get_post_meta($post_id, 'post_reaction_show', true);
        $showreaction = isset($showreaction) ? $showreaction : true;
        var_dump($showreaction);
    }
});

本文标签: functionsGet post id outside loopNotice Trying to get property of nonobject