ターム名の表示方法がわからない
企業サイトによくある「新着情報」欄を作っているところなのですが、どうにもターム名の表示方法がわからないのです。
まず、私はこんな感じのものを作りたいと思っています。
ふつーの「新着情報」です。(ホントは画像のように ALL・お知らせ・イベント というようにタブ別で表示させたいのですが、まだそこまでの段階まで進めてませんので ALL のみです)
これを front-page.php に表示させたいんですが、どこで引っかかっているかと言いますと、
この赤枠で囲った部分です。この部分が表示できなくて困っています。
どうやら「投稿」だった場合は the_category() みたいにするとカテゴリー名が出てくるらしいのですが、今回これは「カスタム投稿タイプ」で作ってしまっておりまして。しかもタクソノミー名じゃなくてターム名(お知らせ・イベント)をそれぞれの記事ごとに表示させたいんです。
###入力してみたコード
以下が front-page.php に入力したコードです。
(カスタム投稿タイプのスラッグが news 、タクソノミーが tax_news、タームを term-osirase、term-event で作成してあります。それとbootstrap4を使用しています)
PHP
1<div class="container news-wrapper"> 2 <h2>新着情報</h2> 3 <?php 4 $args = array ( 5 'posts_per_page'=> 5, 6 'post_type' => 'news', 7 'tax_query' => array ( 8 array ( 9 'taxonomy' => 'tax_news', 10 'field' => 'slug', 11 'terms' => array ( 'term-osirase', 'term-event ' ) 12 ) 13 ) 14 ); 15 ?> 16 <?php $the_query = new WP_Query( $args ); ?> 17 <?php if ( $the_query->have_posts() ) : ?> 18 <dl class="row news-list"> 19 <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 20 <dt class="col"><?php the_time(get_option('date_format')); // ex) 2019年7月14日 ?></dt> 21 <dd class="col badge badge-primary"><?php the_category(); // ←これだと出ない!のはわかってるんだけど、どうやればいいのかがわからない ?></dd> 22 <dd class="col"><a href="<?php the_permalink() ?>"><?php the_title_attribute(); // ex) 本日の◯◯イベントは雨天の為、明日に延期いたします ?></a></dd> 23 <?php endwhile; ?> 24 </dl> 25 <?php endif; ?> 26 <?php wp_reset_query(); ?> 27</div>
もしかして the_category() のところを the_term() みたいにすると出てくるのかなと思いきや、Fatal error発生。
散々ネット上で探すも、そのものズバリを出すコードが見当たらず。出てくるのはほとんど
if ($terms = get_the_terms($post->ID, 'タクソノミー名') { foreach~ }
というヤツばかり。ということはこれを使うんだろうな~、とは思うんですが上記のコードのどこに入れ込めば良いかがわからないでいます。
###色々試してみましたが無理でした
世の中のコーポレートサイトを見れば、こんな「新着情報一覧」なんてみんな簡単そうに実装してるので、絶対ネット上を探せば一つくらい解決方法を書いてるサイトが見つかると思ったんですが……結局どうしてもわかりませんでした。
どなたかお教えいただければ幸いです。どうかよろしくお願いいたします。
###【追記】以下のコードで解決しました
PHP
1<div class="container news-wrapper"> 2 <h2>新着情報</h2> 3 <?php 4 $args = array ( 5 'posts_per_page'=> 5, 6 'post_type' => 'news', 7 'tax_query' => array ( 8 array ( 9 'taxonomy' => 'tax_news', 10 'field' => 'slug', 11 'terms' => array ( 'term-osirase', 'term-event ' ) 12 ) 13 ) 14 ); 15 ?> 16 <?php $the_query = new WP_Query( $args ); ?> 17 <?php if ( $the_query->have_posts() ) : ?> 18 <dl class="row news-list"> 19 <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?> 20 <?php // この部分を追加したらできました! 21 $terms = get_the_terms( get_the_ID(), 'tax_news' ); 22 $term_name = $terms[0]->name; 23 ?> 24 <dt class="col"><?php the_time(get_option('date_format')); // ex) 2019年7月14日 ?></dt> 25 <dd class="col badge badge-primary"><?php echo $term_name; // ex) 後はechoするだけで「お知らせ」って出てきました! ?></dd> 26 <dd class="col"><a href="<?php the_permalink() ?>"><?php the_title_attribute(); // ex) 本日の◯◯イベントは雨天の為、明日に延期いたします ?></a></dd> 27 <?php endwhile; ?> 28 </dl> 29 <?php endif; ?> 30 <?php wp_reset_query(); ?> 31</div>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/07/04 15:10