get_the_ID() gives notice in 404 page

I’m using get_the_ID() in my wp_enqueue_scripts action due to some needs, But as result I’m getting the following notice (wp-debug is on):

Notice: Trying to get property of non-object in C:\wamp\www\WordPress\wp-includes\post-template.php on line 29

I know why this happens, My question is why should this happen? Isn’t WordPress supposed to know that there is no $post assigned to 404 and return an empty result?

Do I have to use:

if( !is_object($post) ) return;

Everywhere I use get_the_ID() in order to get rid of that Notice?

2 s
2

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