WordPressでカスタム投稿の時に表示するタグをよく忘れるので、自分への備忘録も兼ねてご紹介します。
投稿タイプの追加
前提として、functions.phpに以下の記述をして投稿タイプ(カスタム投稿)を追加した場合を想定しています。
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | // 投稿タイプを追加 add_action( 'init' , 'sample_custom_post_type' ); function sample_custom_post_type() { $labels = array ( 'name' => 'サンプル' , 'singular_name' => 'サンプル' , 'add_new_item' => '新しいサンプルを追加' , 'add_new' => '新規追加' , 'new_item' => '新しいサンプル' , 'view_item' => 'サンプルを表示' , 'not_found' => 'サンプルはありません' , 'not_found_in_trash' => 'ゴミ箱にサンプルはありません。' , 'search_items' => 'サンプルを検索' , ); $args = array ( 'labels' => $labels , 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, 'rewrite' => array ( 'slug' => 'sample' , 'with_front' => false), 'hierarchical' => false, 'menu_position' => 4, 'has_archive' => true, 'yarpp_support' => true, 'capability_type' => 'post' , 'supports' => array ( 'title' , 'editor' , 'thumbnail' , 'excerpt' , 'custom-fields' ) ); register_post_type( 'sample' , $args ); register_taxonomy( 'sample-cat' , array ( 'sample' ), array ( 'hierarchical' => true, 'update_count_callback' => '_update_post_term_count' , 'label' => 'カテゴリー' , 'singular_label' => 'カテゴリー' , 'public' => true, 'show_ui' => true, ) ); } |
カスタムタクソノミーを出力
get_the_term_list();を使って表示
01 | echo get_the_term_list( $id , $taxonomy , $before , $sep , $after ); |
「$id」は投稿のIDを指定します。
「$taxonomy」はカスタムタクソノミー名を記述します。
「$before」は指定した文字列が、カスタムタクソノミーの前に表示されます。
「$sep」複数のカスタムタクソノミーがあった場合、区切り文字として表示されます。
「$after」は指定した文字列が、カスタムタクソノミーの後に表示されます。
今回の設定したカスタムタクソノミーを簡単に表示する場合は、以下を出力するテンプレートに記述します。
01 | echo get_the_term_list( $post ->ID, 'sample-cat' ); |
get_the_terms();を使って表示
「get_the_terms」を使って、投稿のカスタムタクソノミーの情報を取得します。
01 | get_the_terms( $id , $taxonomy ); |
表示する時は、「$terms」の中を「foreach」を利用して出力させます。
01 02 03 04 05 | if ( $terms = get_the_terms( $post ->ID, 'sample-cat' )) { foreach ( $terms as $term ) { echo $term ->name; } } |