前提・実現したいこと
Wordpressの特定のカスタム投稿の記事を表示するシングルページに、その記事と同じタームに属する記事の一覧を関連表示したいと思っています。
カスタム投稿タイプ名がtopics、タクソノミー名がtopics_categoryで以下のコードで概ね表示されるのですが、タームが未登録の場合、エラーを返してきます。タームが空の時の条件を追加したいのですが、ご教授いただけると助かります。
ソースコード
<?php global $post; $term = array_shift(get_the_terms($post->ID, 'topics_category')); $args = array( 'numberposts' => 8, //8件表示(デフォルトは5件) 'post_type' => 'topics', //カスタム投稿タイプ名 'taxonomy' => 'topics_category', //タクソノミー名 'term' => $term->slug, //ターム名 'orderby' => 'rand', //ランダム表示 'post__not_in' => array($post->ID) //表示中の記事を除外 ); ?> <?php $myPosts = get_posts($args); if($myPosts) : ?> <?php foreach($myPosts as $post) : setup_postdata($post); ?> <p><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?><?php the_title(); ?></a></p> <?php endforeach; ?> <?php else : ?> <p>関連アイテムはまだありません。</p> <?php endif; wp_reset_postdata(); ?>
回答1件
あなたの回答
tips
プレビュー