[wp]taxonomy.phpで各タームにリンクするselectを作る

コピペで。

こうする

カスタム投稿:custompost
タクソノミー:custompost_taxonomy

<select name="catLink" onChange="location.href=value;">
    <option value="/custompost/">すべての記事</option>
    <?php
        $term = get_queried_object();
        $termEqual = $term->name;
        $termsLink = get_terms('custompost_taxonomy');
        foreach ( $termsLink as $termLink ) {
            if($termLink->name === $termEqual){ $selected = 'selected';}else{ $selected = '';}
            echo '<option value="'.get_term_link($termLink).'" '.$selected.'>'.$termLink->name.'</option>';
        }
    ?>
</select>

optionにタームの一覧を出して、選択したらそれの一覧に遷移する。該当するtermにはselectedが付く。これはarchive.phpとかにそのまま貼っても使えるので便利。

この$termは使い回せるので記事一覧はこうなる。

<?php
    $taxonomy_name  = get_query_var('taxonomy');
    $tax_posts = get_posts(array('post_type' => get_post_type(), 'taxonomy' => $taxonomy_name, 'term' => $taxonomy->slug ) );
    $paged = get_query_var('paged') ? get_query_var('paged') : 1;
    $args = array(
        'posts_per_page' => 10,
        'paged' => $paged,
        'post_type' => 'custompost',
        'post_status' => 'publish',
        'taxonomy' => $taxonomy_name,
        'term' => $term->name,
    );
    $the_query = new WP_Query($args);
    if ( $the_query->have_posts() ) :
?>
    <ul>
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
        <?php endwhile; ?>
    </ul>
<?php else: ?>
    投稿はありません
<?php endif; ?>
<?php wp_reset_query(); ?>

手を入れたほうがいいかも

selectの遷移ギミックをonclickで付けてるんで、ZAP的な意味でセキュリティが甘い状態。

jsなりjQueryなりで別途遷移ギミックを付けたほうが安心。

taxonomy.phpを使わない考え方

urlがダサいことになるのでarchive.phpでやっていくことも一つ。

selectの遷移URLをアーカイブページ+パラメータにして、パラメータにターム情報を入れる。

アーカイブ上でパラメータを拾って記事一覧の条件に突っ込めば、URLはアーカイブのままなので比較的キレイ。

そういうのもあるけど、taxonomy.phpを作らなくてもこのページ自体は生きてるんで、sitemap.xmlから弾くようにしたほうがいいですね。

コメント

タイトルとURLをコピーしました