我想你所有的代码都被包装在循环中了?在操作之前,您应该检查帖子是否确实有附件$images
阵列:
while ( have_posts() ) {
the_post();
if ( has_post_thumbnail() ) {
the_post_thumbnail( /* No need for "post-thumbnail" argument, it\'s the default. */ );
} else {
// No post thumbnail, try attachments instead.
$images = get_posts(
array(
\'post_type\' => \'attachment\',
\'post_mime_type\' => \'image\',
\'post_parent\' => $post->ID,
\'posts_per_page\' => 1, /* Save memory, only need one */
)
);
if ( $images ) {
echo \'<img src="\' . wp_get_attachment_image_src( $images[0]->ID, \'post-thumbnail\' ) . \'" alt="" />\';
}
}
}
请注意,我已经对您的代码进行了一些结构化处理——如果帖子已经有缩略图,则无需加重服务器负担并查询附件。