2

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' );

1 Answer 1

7

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' );
8
  • 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
    Commented Jul 21, 2012 at 3:10
  • @Andrew Where are you adding this code? Commented Jul 21, 2012 at 3:10
  • @RachelBaker NP :) Commented Jul 21, 2012 at 3:12
  • 3
    Hint: isset ( $post->ID ).
    – fuxia
    Commented Jul 21, 2012 at 3:12
  • Ok I think it's a problem with my theme I'm developing, tried the code on another one I'm working on and it's fine. Will post back when I find what's wrong! thanks guys
    – Andrew
    Commented Jul 21, 2012 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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