Add body class based on existance of post thumbnail. Code works but receiving PHP Notice

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:

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

Related posts

Leave a Reply

1 comment

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