
前々からやってみたかった「特定のカテゴリ記事を指定した固定ページに指定数表示」が解決したので、備考録でちょいと。
今でもトップはカテゴリー事に絞り込み表示が出来るようにはしていますが、普通は「お知らせ」だったり、「商品」とか「サービス」とか内容によって固定ページを作って行くと思いますが、直接HTMLを編集するのではなく、投稿内容を編集する事で更新頻度や手軽さを増すことは出来ないかなと考えていました。
自分にはなかなか難しい内容で、理解力が低いという事だと思うのですが、この方法は解りやすかったです。
//特定のカテゴリ記事を指定した固定ページに指定数表示
function show_category_posts($atts) {
$atts = shortcode_atts(array(
‘slug’ => ”, // カテゴリスラッグ(必須)
‘count’ => 5 // 表示する記事数(デフォルト5)
), $atts);
if (!$atts[‘slug’]) return ‘<p>カテゴリが指定されていません。</p>’;
$query = new WP_Query(array(
‘category_name’ => $atts[‘slug’],
‘posts_per_page’ => $atts[‘count’]
));
ob_start();
if ($query->have_posts()):
while ($query->have_posts()): $query->the_post(); ?>
<div class=”post-item”>
<h3><a href=”<?php the_permalink(); ?>”><?php the_title(); ?></a></h3>
<p><?php the_excerpt(); ?></p>
</div>
<?php endwhile;
wp_reset_postdata();
else:
echo ‘<p>記事が見つかりませんでした。</p>’;
endif;
return ob_get_clean();
}
add_shortcode(‘category_posts’, ‘show_category_posts’);
//固定ページに記述
[category_posts slug=”カテゴリー名” count=”5″]
という感じで表示させられました。