Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

What I'm trying to do is add a body class based on whether there is a post thumbnail. The following works, but I get a PHP Notice. How can I fix the PHP Notice below?

function add_featured_image_body_class( $classes ) {

    if( has_post_thumbnail() ) {
        $classes[] = 'has-featured-image';
    }

    return $classes;
}
add_filter( 'body_class', 'add_featured_image_body_class' );

PHP Notice:

PHP Notice:  Trying to get property of non-object in /wp-includes/post-template.php on line 30

This is the function in post-template.php

function get_the_ID() {
  global $post;
  return $post->ID; // this is line 30
}

Update:

Here's what I have now, which seems to work fine without PHP Notices

function add_featured_image_body_class( $classes ) {    
    global $post;

    if ( isset ( $post->ID ) && get_the_post_thumbnail($post->ID)) {
      $classes[] = 'has-featured-image';
    }

    return $classes;
}
add_filter( 'body_class', 'add_featured_image_body_class' );
share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

Try this code:

function add_featured_image_body_class( $classes ) {    
global $post;
    if ( isset ( $post->ID ) && get_the_post_thumbnail($post->ID)) {
          $classes[] = 'has-featured-image';
 }
          return $classes;
}
add_filter( 'body_class', 'add_featured_image_body_class' );
share|improve this answer
    
@BrianFegter Thanks, for the sharp eye! –  Rachel Baker Jul 21 '12 at 3:04
    
Thanks for the answer. That gives me PHP Notice: Trying to get property of non-object on line 25 where line 25 is if (get_the_post_thumbnail($post->ID)) {. I also still have the original PHP notice and for some reason it's doubled. –  Andrew Jul 21 '12 at 3:10
    
@Andrew Where are you adding this code? –  Brian Fegter Jul 21 '12 at 3:10
    
@RachelBaker NP :) –  Brian Fegter Jul 21 '12 at 3:12
1  
Hint: isset ( $post->ID ). –  toscho Jul 21 '12 at 3:12
show 4 more comments

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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