get_the_ID() gives notice in 404 page

get_the_ID() is broken.

function get_the_ID() {
    return get_post()->ID;
}

It tries to use the member ID on a function that returns a post object sometimes:

/* 
 * @return WP_Post|null WP_Post on success or null on failure
 */
function get_post( $post = null, $output = OBJECT, $filter="raw" ) {

get_posts() can return NULL, and NULL has no member ID, because it is not an object.

There is no global post object on a 404 page. And because $post is a global variable, it can be removed everywhere, even on single pages.

So whenever you use get_the_ID(), you have to test for a post object.

if ( get_post() )
{
    $id = get_the_ID();
    // do something
}

There two lessons to learn here:

  1. Never trust the WordPress API. Read the code, understand its limitations.
  2. Avoid global variables in your own code. Treat each one as a serious bug and get rid of it immediately.

Leave a Comment