user3612498 user3612498 - 3 months ago 17
PHP Question

PHP error code: Trying to get property of non-object

When I search on my WordPress site I get the following error: Notice: Trying to get property of non-object in archive-product.php on line 20

Line 20 in that php file is

$postid = $wp_query->post->ID;


Any suggestions on how I can fix this? For reference the immediate code before and after line 20 is below.

<?php //Display Page Header
global $wp_query;
$postid = $wp_query->post->ID;
echo page_header( get_post_meta($postid, 'qns_page_header_image', true) );
wp_reset_query();
?>


Thank you,
Ryan

Answer

So that means $wp_query->post is not an object. I havn't used worpress much but It looks like one of the posts must be returning an empty object.

Try this in order to skip over any empty post:

<?php //Display Page Header
    global $wp_query;
    if(!empty($wp_query->post){
        $postid = $wp_query->post->ID;
        echo page_header( get_post_meta($postid, 'qns_page_header_image', true) );
    }
    wp_reset_query();
?>