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?

  • This question is out-of-date for WordPress 4.0 and later. get_the_ID() can now be safely called anywhere its defined without raising a warning, even if there is no global $post set. Commented Aug 3, 2020 at 17:02

2 Answers 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.
  • I had a bunch of warnings on 404 pages too, all related to the $post object. Is it better to create and use a function like so, pastebin.com/EwEZAQzi on locations it makes sense? My main issue is that I use the post object to create localised JS vars ( using post meta ) in functions.php, which still runs on a 404 page.
    – Tim
    Commented Dec 15, 2015 at 13:04
  • @Tim Just don't run you script on 404 pages. Check for is_singular() before you are enqueuing the script.
    – fuxia
    Commented Dec 15, 2015 at 15:01

You can check to see if you're in a 404 page:

if( is_404() ) {
// ...




Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.