HAS_POST_缩略图上的误报

时间:2017-04-19 作者:MikeiLL

在循环中,对于没有特色图像的帖子(自定义帖子类型):

  1. has_post_thumbnail() (有无规定$post->ID) 正在返回true, 而get_the_post_thumbnail(), 还有我们没有$post->ID 返回空字符串
循环:

$args = array(
\'post_type\' => \'customs\', 
\'post_status\' => \'publish\',
\'fields\' => \'id\',
\'posts_per_page\' => -1
);
$query = new WP_Query($args);
while ( $query->have_posts() ) : $query->the_post(); 
  has_post_thumbnail();
  the_title(); // as expected
  the_excerpt(); // as expected
endwhile;
CPT定义如下:

    $name          = \'Custom\';
    $singular_name = \'Custom\';
    $slug          = \'custom\';
    $menu_icon     = \'universal-access\';

    // Declare args and apply filters
    $args = array(
        \'labels\' => array(
            \'name\' => $name,
            \'singular_name\' => $singular_name,
            \'add_new\' => __( \'Add New\', \'total\' ),
            \'add_new_item\' => __( \'Add New Item\', \'total\' ),
            \'edit_item\' => __( \'Edit Item\', \'total\' ),
            \'new_item\' => __( \'Add New Custom Item\', \'total\' ),
            \'view_item\' => __( \'View Item\', \'total\' ),
            \'search_items\' => __( \'Search Items\', \'total\' ),
            \'not_found\' => __( \'No Items Found\', \'total\' ),
            \'not_found_in_trash\' => __( \'No Items Found In Trash\', \'total\' )
        ),
        \'public\' => true,
        \'supports\' => array(
            \'title\',
            \'editor\',
            \'excerpt\',
            \'thumbnail\',
            // \'comments\',
            \'custom-fields\',
            \'revisions\',
            \'author\',
            \'page-attributes\',
        ),
        \'capability_type\' => \'post\',
        \'rewrite\' => array( \'slug\' => $slug, \'with_front\' => false ),
        \'has_archive\' => true,
        \'menu_icon\' => \'dashicons-\'. $menu_icon,
        \'menu_position\' => 20,
    );

    // Register the post type
    register_post_type( \'customs\', $args );

}
虽然我可以通过以下方式获得期望的结果:

if (get_the_post_thumbnail() !== \'\'):
  // display the thumbnail
else:
  // some other option
endif;
我相信这不是解决办法。我还能到哪里去探究是什么导致了这种意想不到的结果呢?

1 个回复
SO网友:Vinod Dalvi

我已经在我的测试站点上测试了您上面共享的代码,但它对我来说运行良好,没有任何问题。

您似乎正面临本页所述的问题WordPress has_post_thumbnail() not working – How to fix the phantom featured image issue 您可能会遇到这种情况,尤其是在处理迁移的内容时,或者由于某种原因,您的数据库有点奇怪。

因此,您可以使用如下代码来检查是否存在附加到post的缩略图,而不是has\\u post\\u thumbnail()。

$img_url = wp_get_attachment_url( get_post_thumbnail_id() );

if  ( ! empty( $img_url ) ) {

 // Do what you want to do if featured image is set to post
}

相关推荐