ワードプレスのテーマtwentytwentyを基盤に、カスタムフィールドの真偽値を使って一覧表示したい投稿を絞り込む実装をしたので、備忘録的にこの記事を残す。
環境情報
PHP:version 7.3.12
WordPress:version 5.5.3
WPテーマ:twentytwenty
作業
<div class="section_inner">
<h2>カスタム投稿 真/偽での振り分け</h2>
<div class="contents">
<?php $args = array(
'post_type' => array('sample_01', 'sample_02'),/*カスタム投稿タイプの名前*/
'showposts' => 4,
'meta_key' => 'new',/*カスタムフィールドのフィールド名*/
'meta_value' => true,/*カスタムフィールドの値*/
);
$customPosts = get_posts($args);
if ($customPosts) : foreach ($customPosts as $post) : setup_postdata($post); ?>
<a href="<?php the_permalink(); ?>">
<?php the_title(); ?>
<div class="title"><?php the_field('title'); ?></div>
<div class="thumbnail"><?php echo wp_get_attachment_image(get_post_meta($post->ID, 'thumbnail', true), 'thumbnailSmall'); ?></div>
</a>
<?php endforeach; ?>
<?php else : ?>
<p>記事はありません。</p>
<?php endif;
wp_reset_postdata(); ?>
</div>
</div>