Get post id outside loop : Notice: Trying to get property of non-object

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

Topic loop functions posts Wordpress

Category Web


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

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]'); ?> 

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:

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.