Wordpressのカスタム投稿タイプでカテゴリ別に出力する方法
Wordpress初心者の備忘録です。
よくある質問のようなカスタム投稿タイプでカテゴリ別に出力したい時に行った実装です。
環境
完成イメージ
↓こんな感じの画面を実装します。
ソース
▼functions.php
<?php //カスタム投稿を追加 function add_custom_post(){ //よくある質問 register_post_type( 'question', array( 'labels' => array( 'name' => 'よくある質問', 'singular_name' => 'よくある質問', ), 'public' => false, 'show_ui' => true, 'menu_position' => 6, 'has_archive' => true, 'hierarchical' => false, 'supports' => array( 'title', 'editor', ), ) ); register_taxonomy_for_object_type('category', 'article'); register_taxonomy_for_object_type('post_tag', 'article'); } add_action('init', 'add_custom_post', 1); //カスタムタクソノミーを追加 function add_taxonomy() { //よくある質問カテゴリ register_taxonomy( 'faq-cat', 'question', array( 'label' => 'よくある質問カテゴリ', 'singular_label' => 'よくある質問カテゴリ', 'labels' => array( 'all_items' => 'よくある質問カテゴリ一覧', 'add_new_item' => 'よくある質問カテゴリを追加' ), 'public' => true, 'show_ui' => true, 'show_in_nav_menus' => true, 'hierarchical' => true ) ); } add_action( 'init', 'add_taxonomy' ); ?>
固定ページで、よくある質問を作ったのでpage.phpを変更します。
該当箇所を抜粋したのが以下のソースです。
▼page.php
<?php $taxonomies = 'faq-cat'; $args = array( 'taxonomy' => $taxonomies, 'hide_empty' => true, // 空のカテゴリを出力しない場合はtrue ); $terms = get_terms($args); // カテゴリー別に記事を出力する foreach($terms as $term): $args = array( 'post_type' => 'question', 'taxonomy' => $taxonomies, 'term' => $term->slug, 'posts_per_page'=> -1 ); $faq_posts = get_posts($args); echo '<section>'; echo '<h2>'.$term->name.'</h2>'; foreach($faq_posts as $faq_post): setup_postdata( $faq_post ); ?> <div> <a> <dl> <dt>Q.</dt> <dd><?php echo $faq_post->post_title; ?></dd> </dl> </a> <ul> <li> <dl> <dt>A.</dt> <dd> <?php the_content(); ?> </dd> </dl> </li> </ul> </div> <?php endforeach; echo '</section>'; endforeach; wp_reset_postdata(); ?>
ソースを少し解説します。
get_terms($args)
これでカテゴリの一覧を取得します。
$taxonomies = 'faq-cat';
で該当のカスタムタクソノミー (カテゴリー)を指定しています。
foreach($terms as $term): echo '<h2>'.$term->name.'</h2>'; endforeach;
でループし、カテゴリーの名前を出力しています。
get_posts($args)
これで投稿記事の一覧を取得します。
$args = array( 'post_type' => 'question',//カスタム投稿タイプ名(スラッグ)指定 'taxonomy' => $taxonomies,//タクソノミー名指定 'term' => $term->slug,//カテゴリのスラッグを指定 'posts_per_page'=> -1 );
この条件で、該当カテゴリの投稿記事の一覧を取得します。
以上です。
文法間違い等あれば、ご指摘をお願いします。
構築の流れをだいぶ分かってきたけど、記事の出力の仕方が複数パターンあるので違いを覚えて行きたいな。