function.php にショートコードを作成して、固定ページにあるカテゴリに所属する一覧を出します。
例えばショップリストをカスタム投稿に登録しておき、固定ページで「アイスクリームが売ってるショップ一覧はこちら」みたいなことができます。
次のプログラムをコピーして function.php の一番下に追記してください。
まあちょっと長いですが、なんてことないです!
// まずはカスタム投稿タイプを追加(ショップリスト)
add_action( 'init', 'create_post_type' );
function create_post_type() {
register_post_type( 'shoplist', // 1.投稿タイプ名の定義
array(
'labels' => array(
'name' => __( 'ショップリスト' ), // 2.表示する投稿タイプ名
'singular_name' => __( 'ShopList' )//3.このカスタム投稿の識別名
),
'public' => true,
'menu_position' =>5,//管理画面のメニューの順番
'supports' => array('title','editor','thumbnail','custom-fields'
), //編集画面で使用するフィールド
)
);
}
// カスタム投稿タイプ(ショップリスト)に対してカテゴリ追加
add_action( 'init', function () {
register_taxonomy( 'icecream',//カテゴリ名:icecream
'shoplist',//追加したいカスタム投稿名:shoplist
array(
'label' => __( 'アイスクリーム' ),//表示されるカテゴリ名
'hierarchical' => true,
'update_count_callback' => '_update_post_term_count',
'public' => true,
'show_ui' => true
)
);
} );
//固定ページにカスタム投稿の"shoplist"のアーカイブを出すショートコード
//ショートコードの使い方:[feed tax="カテゴリ名" term1="所属するカテゴリ" limit="表示件数"]
function section_feed_shortcode( $atts ) {
extract( shortcode_atts( array( 'limit' => -1, 'tax' => 'taxonomy', 'term1' => 'terms', 'term2' => 'terms', 'term3' => 'terms', 'term4' => 'terms', 'term5' => 'terms'), $atts ) );
$paged = get_query_var('paged') ? get_query_var('paged') : 1;
query_posts( array (
'posts_per_page' => $limit,
'post_type' => 'shoplist', //投稿タイプ名postは通常の投稿
'order' => 'ASC',
'orderby' =>'meta_value',
'tax_query' => array(
array(
'taxonomy' => $tax, //タクソノミー名をショートコードの引数で受け取る
'field' => 'slug',
'terms' => array( $term1,$term2,$term3,$term4,$term5 )
//'terms' => $term //タームのスラッグをショートコードの引数で受け取る
)
),
'paged' => $paged ) );
$list = ' ';
while ( have_posts() ) { the_post();
//所属するタームの取得
$terms = get_the_terms($post->ID, 'icecream'); $icecream_tax=''; foreach((array)$terms as $term){$term_name = $term->name; $icecream_tax = $icecream_tax.$term_name.'<br>'; };//所属するカテゴリ名を取得
$list .= '<div>'
. '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>' //カスタム投稿のタイトルを取得
. '<table class="th_gray t-s sp_t-s">'
. '<tr><th width="31%">売ってるもの</th><td>' . $icecream_tax . '</td></tr>' //売ってるものにアイスクリームと表示させる
. '<tr><th>カスタムフィールド</th><td>' . get_post_meta(get_the_ID(), 'カスタムフィールド名', true) . '</td></tr>' //取得したいカスタムフィールドがあれば取得
. '</table>'
. '</div>';
}
return
'<div class="listings clearfix">'
. $list
. '<div class="nav-previous">' . get_next_posts_link( __( '<span class="meta-nav">←</span> Older posts' ) ) . '</div>'
. '<div class="nav-next">' . get_previous_posts_link( __( 'Newer posts <span class="meta-nav">→</span>' ) ) . '</div>'
. '</div>' .
wp_reset_query();
}
add_shortcode( 'feed', 'section_feed_shortcode' );
. '&</div>' .
これで[feed]というショートコードができました。
固定ページにいって以下を記述すれば「アイスクリーム」が売っている店の一覧が表示されます。
[feed tax="icecream" term1="アイスクリーム"]
ちなみにアイスクリームカテゴリに、アイスクリーム・ラクトアイス・かき氷・ジェラートなど、複数のカテゴリがある場合は以下の表記で、複数に所属する店の一覧を出せます。
[feed tax="icecream" term1="アイスクリーム" term2="かき氷"]
これで「アイスクリーム」か、「かき氷」が売ってる店の一覧が出ます。
