前提・実現したいこと
投稿詳細ページで下記条件で関連記事を表示したく思っています。
カスタムタクソノミーを設定しています。
- 同じカテゴリーと同じターム両方がついた記事を優先して表示する
- 次に「同じカテゴリー」の記事を表示させる
- 関連記事の合計は3つになるようにする
発生している問題・エラーメッセージ
- 同じカテゴリーと同じターム両方がついている記事が存在する場合は希望通りの表示となるが、それ以外は関連記事が「0件」になってしまう。
※例えば同じカテゴリーや同じタームがついた記事が存在している場合も0件表示になってしまう。
- 1つ目と2つ目のループを<ul>で分断せず、1つのリストとして出力したい。
ソースが長くなってしまうためループの部分は省略していますが必要あれば提示します。
宜しくお願いします。
php
1 2<?php 3 4 5$ppp = 3; //表示件数 6 7 8$categories = get_the_category(); 9$category_ID = array(); 10if($categories) { 11 foreach ($categories as $category) { 12 array_push( $category_ID, $category->cat_ID); 13 } 14} 15 16$terms = get_the_terms($post->ID,'my_taxonomy'); 17$terms_ID = array(); 18if($terms) { 19 foreach ($terms as $term) { 20 array_push($terms_ID, $term->term_id); 21 } 22} 23 24$args = array( 25 'post__not_in' => array($post->ID), 26 'category__in' => $category_ID, 27 'posts_per_page'=> $ppp, 28 'orderby' => 'date', 29 'tax_query' => array( 30 array( 31 'taxonomy' => 'my_taxonomy', 32 'field' => 'term_id', 33 'terms' => $terms_ID, 34 ), 35 ), 36); 37$related_posts = new WP_Query($args); 38 39$related_posts_count = $related_posts->post_count; 40$first_post_ids = array(); 41 42if($related_posts->have_posts()): ?> 43<ul> 44<?php while ($related_posts-> have_posts()) : $related_posts->the_post(); ?> 45<?php 46$get_id = get_the_ID(); 47array_push($first_post_ids, $get_id); 48?> 49 50//ループ処理 51 52<?php endwhile; ?> 53<?php 54$second_ppp = $ppp - $related_posts_count; 55?> 56</ul> 57<?php endif; ?> 58<?php wp_reset_postdata(); ?> 59 60<?php 61if($second_ppp > 0) { 62 63$args = array( 64 'post__not_in' => array_merge(array($post->ID), $first_post_ids), 65 'category__in' => $category_ID, 66 'posts_per_page'=> $ppp - $related_posts_count, 67 'orderby' => 'date', 68); 69$related_posts = new WP_Query($args); 70if($related_posts->have_posts()): ?> 71 72<ul> 73<?php while ($related_posts-> have_posts()) : $related_posts->the_post(); ?> 74 75//ループ処理 76 77<?php endwhile; ?> 78</ul> 79<?php endif; ?> 80<?php wp_reset_postdata(); 81 82} ?> 83
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/07/20 06:48
2018/07/20 06:57
2018/07/20 07:04