アイキャッチの有無で条件分岐する場合はhas_post_thumbnail()
で振り分けすればいいのですが…
今回は投稿一覧を取得する段階でアイキャッチ画像がある・ないで絞り込みをする必要が出てきたので、get_posts()
でのパラメーターの指定方法をメモしておきます。
カスタムフィールドを条件にして絞り込む
get_posts
で アイキャッチ画像のあり・なしの絞り込みをするときはカスタムフィールド_thumbnail_id
を条件に絞り込みをすると良さそうです

まずは試しに以下のような投稿一覧を表示するコードを作ってみました
<?php
$posts = get_posts( array(
'posts_per_page' => 5,
) );
if ( $posts ) :
foreach ( $posts as $post ) :
?>
<h2><?php echo esc_html( $post->post_title ); ?></h2>
<?php
if ( has_post_thumbnail( $post->ID ) ) {
echo get_the_post_thumbnail( $post->ID, 'thumbnail' );
}
?>
<?php
endforeach;
endif;
?>
このコードにアイキャッチでの絞り込みを加えていきます
アイキャッチ画像「あり」で絞り込む
アイキャッチ画像ありで絞り込みをする場合はmeta_key
に_thumbnail_id
を指定するだけでOKです
<?php
$posts = get_posts( array(
'posts_per_page' => 5,
'meta_key' => '_thumbnail_id',
) );
if ( $posts ) :
foreach ( $posts as $post ) :
?>
<h2><?php echo esc_html( $post->post_title ); ?></h2>
<?php
if ( has_post_thumbnail( $post->ID ) ) {
echo get_the_post_thumbnail( $post->ID, 'thumbnail' );
}
?>
<?php
endforeach;
endif;
?>

期待通り、アイキャッチ画像が指定された投稿だけ表示されました!
アイキャッチ画像「なし」で絞り込む
アイキャッチ画像「なし」の絞り込みをする場合は、「カスタムフィールドに_thumbnail_id
が無い投稿」が条件になります
カスタムフィールドでの絞り込みに使えるパラメータを探して…
https://wpdocs.osdn.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/WP_Query#Custom_Field_Parametersmeta_compare
にNOT EXISTS
を指定してあげます
<?php
$posts = get_posts( array(
'posts_per_page' => 5,
'meta_key' => '_thumbnail_id',
'meta_compare' => 'NOT EXISTS',
) );
if ( $posts ) :
foreach ( $posts as $post ) :
?>
<h2><?php echo esc_html( $post->post_title ); ?></h2>
<?php
if ( has_post_thumbnail( $post->ID ) ) {
echo get_the_post_thumbnail( $post->ID, 'thumbnail' );
}
?>
<?php
endforeach;
endif;
?>

無事アイキャッチの無い投稿だけが表示されました
まとめ
ループ内であればhas_post_thumbnail()
で条件分岐できますが、そもそも投稿一覧を取得する段階で絞り込みする場合は今回のような条件を指定してあげる必要がありますね
もし必要になりましたご参考にしてみて下さい。
ではまた。