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

  • Are you trying to get the id of the post when on a single post view only? – Jacob Peattie Sep 12 '17 at 14:48
  • 1
    The query hasn't run yet on the init action, it's too early. – Milo Sep 12 '17 at 15:33
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]'); ?> 
  • If there is no global post, your code will throw the same notice as stated in the question. – fuxia Nov 14 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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