0

I need to capture the current page id, execute some conditional script in footer, in my own plugin function hooks to wp_footer.

Here is my plugin code, but page id returning wrong value?

<?php
/*
  Plugin Name: My Plugin
  Author:  GS
  Version: 1.1
*/
Function footer_page_id()
{
  global $post;
  echo '<div> page_id:'.$post->ID.'</div>';// output wrong value
  global $wp_query;      
  echo 'page_id:'.get_the_ID();// output wrong value
  echo 'post_id:'.$wp_query->post->ID; // output wrong value
  echo 'page_id:'.$wp_query->get_queried_object_id(); // output always 0
  echo'</br>';exit;
}
 add_action('wp_footer', ' footer_page_id ');
?>

Thanks in advance.

  • 1
    You may need to reset the $wp_query — try this: add wp_reset_query(); after the global $post;. – Sally CJ Sep 26 '18 at 10:29
0

To get the current page ID outside of The Loop, you need to use get_queried_object_id(); ($wp_query-> is unnecessary).

However, this will only work when you are viewing a single Page (so anything under Pages > All Pages in the back-end).

If you are viewing the blog, an archive, or a category it will not be a valid page ID. On categories it will return the category ID, but on archives or the blog it will not have a value because those things do not have an ID.

If your theme or another plugin uses query_posts(), this could interfere with this function. Using wp_reset_query() will fix this, but whichever theme or plugin is running query_posts() should be doing this.

If you are using query_posts(), don't. Use a custom query with new WP_Query() or get_posts().

0

for above requirement you can rewrite the code like this

function footer_page_id()
{
  global $post;
  echo '<div> page_id:'.$post->ID.'</div>';
 // remaining codes here

}
 add_action('wp_footer', 'footer_page_id');

Please note that inorder to check the value of a variable inside a wordpress function please use debug log technique.

First enable debugging as per wordpress official tutorial https://codex.wordpress.org/Debugging_in_WordPress

Then you can find debugg.log file inside wp-content folder

function footer_page_id()
{
  global $post;
  echo '<div> page_id:'.$post->ID.'</div>';// output wrong value
  error_log(print_r($post->ID,true));


}
 add_action('wp_footer', 'footer_page_id');

Like this you can check the variable values in plugin.

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.