0

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

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' );
  • 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
  • 3
    Hint: isset ( $post->ID ). – fuxia Jul 21 '12 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 Jul 21 '12 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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