WordPressで最新投稿を一覧表示したいけど、初期の投稿を表示するブロックはカテゴリーが表示できません。そして、投稿日とタイトルの表示だけでなく、カテゴリーも表示したいという要望は少なくありません。ショートコードを使うことでプラグインに頼らず軽量に実装できます。
今回はカテゴリを絞ったり、デザインをカスタマイズしたい…そんなニーズに応えるショートコードを作りました。
この記事では、1つのショートコードで全カテゴリー表示も特定カテゴリ表示も実現する方法の覚書です。
このショートコードの特徴
カテゴリー表示の柔軟性
投稿にカテゴリー名を自動で表示。また、カテゴリースラッグをクラス名として出力するので、カテゴリー別に色を変えるなどのデザインもCSSで自由にカスタマイズ可能!
特定カテゴリー対応
category属性で特定のカテゴリー(例: newsやevents)を指定可能。また、複数カテゴリもカンマ区切りでOK!
カテゴリを指定しない場合は全投稿を表示するので、1つのショートコードで多目的に使えます。
投稿数の変更可能
投稿数(posts_per_page)を自由に設定可能。5件、10件など、サイトのニーズに合わせて表示件数を調整できます。
functions.phpへの追加方法
下記をコピーしfunctions.phpにペーストします。
function custom_latest_posts_with_category($atts) {
$atts = shortcode_atts(
array(
'posts_per_page' => 10, // 件数を設定(例は10件)
'category' => '', // カテゴリ名またはスラッグを指定可能(カンマ区切り対応)
),
$atts
);
$args = array(
'posts_per_page' => intval($atts['posts_per_page']),
);
if (!empty($atts['category'])) {
$categories = sanitize_text_field($atts['category']);
$args['category_name'] = implode(',', array_map('trim', explode(',', $categories)));
}
$latest_posts = new WP_Query($args);
if ($latest_posts->have_posts()) {
$output = '<div class="custom-latest-posts">';
while ($latest_posts->have_posts()) {
$latest_posts->the_post();
$categories = get_the_category();
$output .= '<div class="latest-post-item">';
$output .= '<div class="post-meta">';
$post_date = get_the_date('Y年n月j日');
$output .= '<p class="post-date">' . esc_html($post_date) . '</p>';
$output .= '<div class="category-names">';
foreach ($categories as $category) {
$output .= '<span class="category-name ' . esc_attr($category->slug) . '">' . esc_html($category->name) . '</span>';
}
$output .= '</div>'; // category-names
$output .= '</div>'; // post-meta
$output .= '<h3><a href="' . get_permalink() . '">' . get_the_title() . '</a></h3>';
$output .= '</div>'; // latest-post-item
}
wp_reset_postdata();
$output .= '</div>'; // custom-latest-posts
} else {
$output = '<p>最新の投稿はありません。</p>';
}
return $output;
}
add_shortcode('latest_posts_with_category', 'custom_latest_posts_with_category');
ショートコードの使用例
全カテゴリー
[latest_posts_with_category posts_per_page="10"]
投稿記事を10件表示する
特定カテゴリー
[latest_posts_with_category posts_per_page="10" category="news"]
スラッグがnewsのカテゴリーの投稿を10件表示する
複数カテゴリー
[latest_posts_with_category posts_per_page="10" category="news,events"]
スラッグがnews,eventsのカテゴリーの投稿を10件表示する
注意点
カテゴリスラッグを正確に入力します。
※カテゴリ名(例: 「ニュース」)は使えないので注意
その他
カスタム投稿タイプ対応
$args['post_type'] = 'custom_post';
上記を追加でカスタム投稿タイプにも対応できます。
その他サムネイル画像を取得して入れたり柔軟性を高めてください。
使用例
- ニュースサイトでcategory="news"で最新ニュースだけトップページに表示したい場合。
- ブログサイトでcategory="tips,reviews"で特定ジャンルの記事をサイドバーに表示したい場合。
- ポートフォリオでカテゴリごとの作品一覧をショートコードで簡単に実装!
まとめ
最新投稿一覧のブロックでは物足りない場合、もうすこしカスタマイズしたい場合に使ってみてください。