我想做的是根据是否有帖子缩略图添加一个body类。下面的内容很有效,但我收到了一个PHP通知。如何修复下面的PHP通知?
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注意事项:
PHP Notice: Trying to get property of non-object in /wp-includes/post-template.php on line 30
这是post模板中的函数。php
function get_the_ID() {
global $post;
return $post->ID; // this is line 30
}
Update:
下面是我现在所拥有的,在没有PHP通知的情况下,它似乎可以正常工作
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\' );
最合适的回答,由SO网友:Rachel Baker 整理而成
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\' );