I have a 404.php
template for my theme. I also have WP_DEBUG
in wp-config.php set to TRUE
.
Consider this 404 template:
get_header(); ?>
<div id="content" style="full-width">
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<div class="post-content">
Whatever.
</div>
</div>
</div>
<?php get_footer(); ?>
I get the following error:
Notice: Trying to get property of non-object in …/path/post-template.php on line 30
Now I know the error is caused by the call to the_ID()
on line 4. And the easiest solution would be for me to just remove it in the template.
However, there are places in other template parts, header.php
for instance, that either calls the same function or uses $post->ID
.
An example would be $project_meta = get_post_meta($post->ID, 'show_project_meta', true);
. This is shared and works fine in any other template, i.e where the page has a post/page ID. What can I do for the 404 page?
Is there a way to fix this? Thanks.
2 Answers
The 404.php
template file is used for 404
errors: i.e. no posts found.
Since there are no posts, there is no $post
object. With no $post
object, functions such as the_ID()
are not available, and will return the error you’re observing.
The fix: replace all instances of $post
-derived data with static data. e.g. replace this:
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
…with this:
<div id="post-0" <?php post_class(); ?>>