【WordPress】タクソノミーで抽出条件を記述する方法について(表示中の投稿と同じタームに分類された投稿の表示方法)

【WordPress】タクソノミーで抽出条件を記述する方法について(表示中の投稿と同じタームに分類された投稿の表示方法)

通常ですと、wordpressのカテゴリーで抽出条件を記述する場合が多いですが、

たとえば、プラグインの advance custom field と Custom Post Type UI を利用して

複数の投稿記事を結合してadvance custom fieldで設定した項目内容を表示する方法をご紹介します。

<?php // 現在表示されている投稿と同じタームに分類された投稿を取得
$taxonomy_slug = 'product-categories'; // タクソノミーのスラッグを指定
$post_type_slug = 'products'; // 投稿タイプのスラッグを指定
$post_terms = wp_get_object_terms($post->ID, $taxonomy_slug); // タクソノミーの指定
if( $post_terms && !is_wp_error($post_terms)) { // 値があるときに作動
$terms_slug = array(); // 配列のセット
foreach( $post_terms as $value ){ // 配列の作成
$terms_slug[] = $value->slug; // タームのスラッグを配列に追加
}
}
$args = array(
'post_type' => $post_type_slug, // 投稿タイプを指定
'posts_per_page' => 5, // 表示件数を指定
'orderby' => 'rand', // ランダムに投稿を取得
'post__not_in' => array($post->ID), // 現在の投稿を除外
'tax_query' => array( // タクソノミーパラメーターを使用
array(
'taxonomy' => $taxonomy_slug, // タームを取得タクソノミーを指定
'field' => 'slug', // スラッグに一致するタームを返す
'terms' => $terms_slug // タームの配列を指定
)
)
);
$the_query = new WP_Query($args); if($the_query->have_posts()):
?>
<?php while ($the_query->have_posts()): $the_query->the_post(); ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>

参照元サイト
https://hirashimatakumi.com/blog/4226.html

関連記事

  1. テレワークに必要な機器について

  2. ループを連続で使用する場合の注意点 wp_reset_postdata…

  3. wordpress カテゴリーページのディスクリプション設置方法につ…

  4. wordpress プラグインを利用しないで検索カスタマイズする方法…

  5. 検索エンジン(robot)に特定のディレクトリだけインデックスさせない…

  6. 「先頭に固定表示」を指定した記事を表示、その記事を除いて残り投稿をルー…