0

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 :(

2
  • Are you trying to get the id of the post when on a single post view only? Sep 12, 2017 at 14:48
  • 1
    The query hasn't run yet on the init action, it's too early.
    – Milo
    Sep 12, 2017 at 15:33

3 Answers 3

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:

0

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]'); ?> 
1
  • If there is no global post, your code will throw the same notice as stated in the question.
    – fuxia
    Nov 14, 2019 at 0:11
0

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);
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.