Trying to get property of non-object when using $post->post_parent

I have debug set to true and to display different banners I am using conditional tags such as:

<?php

if ( is_page( 'about' ) || '2' == $post->post_parent ) {    
    // the page is "About", or the parent of the page is "About"
    $bannerimg = 'about.jpg';

} elseif ( is_page( 'learning' ) || '56' == $post->post_parent ) {  
    $bannerimg = 'teaching.jpg';

} elseif ( is_page( 'admissions' ) || '15' == $post->post_parent ) { 
    $bannerimg = 'admissions.jpg';

} else { 
    $bannerimg = 'home.jpg'; // just in case we are at an unclassified page, perhaps the home page
}   

?>

This results in error like:

Read More
[24-Sep-2013 00:03:32] PHP Notice:  Trying to get property of non-object in D:Clientsproject1www.project1.devwp-contentthemescustom_v1header.php on line 100

Removing $post->post_parent fixes the PHP notice. Can anyone let me know if am doing anything wrong?

Location of this code:

I am using code structure similar to above in my header.php file. This is not inside any post loop. The cost I pasted above is from http://codex.wordpress.org/Conditional_Tags

Purpose of my code:
Based on what page the user is, I need to display different banners. So every page and its sub-pages have the same banner.

if ( is_page('114') || $post->post_parent == '114' ) { }

Even above code generates the error. Not sure why $post->post_parentis not considered an object.

Related posts

2 comments

  1. @kaiser answer gives you the solution. I see from your comment that you don’t understand, so I upvoted his answer and translate it in code:

    <?php
    $bannerimg = 'home.jpg';
    $post = is_singular() ? get_queried_object() : false;
    if ( ! empty($post) && is_a($post, 'WP_Post') ) {
      if ( 'about' == $post->post_name || '2' == $post->post_parent ) {    
        $bannerimg = 'about.jpg';
      } elseif ( 'learning' == $post->post_name || '56' == $post->post_parent) ) {  
        $bannerimg = 'teaching.jpg';
      } elseif ( 'admissions' == $post->post_name || '15' == $post->post_parent ) { 
        $bannerimg = 'admissions.jpg';
      }
    }
    
  2. Normally $post should be an object which is an instanceof WP_Post. The object normally has a default of 0 if

    • no parent is set
    • the post type is not hierarchical

    So the only thing that can be here is that the post object isn’t set up properly. Make sure you’re inside a loop, have called the_post() or $custom_query->the_post() or used setup_postdata( $post );.

    Btw, if you have if/elseif/else, you normally could avoid the else as it’s similar to the default in a switch. Just set $bannerimg = 'foo'; before the if.

Comments are closed.