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:wampwwwWordPresswp-includespost-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?
get_the_ID()
is broken.It tries to use the member
ID
on a function that returns apost
object sometimes:get_posts()
can returnNULL
, andNULL
has no memberID
, 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 apost
object.There two lessons to learn here:
You can check to see if you’re in a 404 page:
Reference
is_404()