Blog

WordPress get_the_ID() function does not work correctly in Posts Page

 

We recently found a problem in one of our sites with the Posts Page. We executed a function that with ID of the page show different Footer and Header. But with the line of code classic $post->ID or get_the_ID(), in the Posts Page not return the Id of the Posts Page otherwise return the Id of the first post in loop.

So, let’s talk in code!

If we have something like this:

function something_to_test( $header_or_footer_key ) {

   global $post;
  
$something_to_show_id = null;

   if  ( $post ) {
         
$something_to_show_id = get_something_to_show_meta( str_replace( ‘-‘, ‘_’, $header_or_footer_key ), get_the_ID() );
                 }

 

}

And in database you set that for the postID=455 the $header_or_footer_key=25

And calling the function something_to_test( $header_or_footer_key ) into header.php for the Posts Page the line get_the_ID() return the $post->ID for the first posted into the page of the posts in your site.