没有缩略图的帖子不需要ID。使用元查询仅获取具有缩略图的内容。
添加元查询
function get_only_posts_with_images( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( \'meta_query\', array( array( \'key\' => \'_thumbnail_id\' ) ) );
}
}
add_action( \'pre_get_posts\', \'get_only_posts_with_images\' );
或使用自定义查询。
$query = "
SELECT posts.*
FROM $wpdb->posts AS posts
INNER JOIN $wpdb->posts AS attachment
ON attachment.`post_parent`=posts.`ID`
AND attachment.`post_type`=\'attachment\'
WHERE posts.`post_type`=\'post\'
";
$posts_with_images = $wpdb->get_results( $query, OBJECT );