はじめに
「新着記事」や「人気記事」は、catsオプションを使ってカテゴリーごとに絞り込んで表示できます。
カテゴリーページや投稿ページにおいてこのcatsオプションを自動的に設定し、該当カテゴリーの情報だけを表示します。
この記事では、この方法について説明します。
使用方法
actionオプションを追加します。
- 新着記事
[new_list action="category"]
- 人気記事
[popular_list action="category"]
実装手順
以下の手順で実装します。
- ラベルPHPを追加
以下のコードをfunctions.phpに追加します。
/** * ショートコードの属性にカテゴリIDを自動設定 * * @param array $out デフォルトのショートコード属性 * @param array $pairs デフォルト値の配列 * @param array $atts ショートコードの属性 * @param string $shortcode ショートコード名 * @return array 修正後のショートコード属性 */ if (!function_exists('set_cats_from_category_or_post')): function set_cats_from_category_or_post($out, $pairs, $atts, $shortcode) { if (empty($atts['action']) || $atts['action'] !== 'category') { return $out; } // 投稿またはカテゴリーページ以外は非表示に設定 if (!is_single() && !is_category()) { $out['class'] = ($out['class'] ?? '') . ' is-hidden'; return $out; } switch (true) { case is_category(): $category = get_queried_object(); if ($category && isset($category->term_id)) { $out['cats'] = $category->term_id; } break; case is_single(): $post_id = get_the_ID(); // メインカテゴリーを取得 $main_cat_id = get_the_page_main_category($post_id); if ($main_cat_id && in_category($main_cat_id, $post_id)) { $category = get_category($main_cat_id); if ($category && isset($category->term_id)) { $out['cats'] = $category->term_id; break; } } // メインカテゴリーがない場合 $categories = get_the_category($post_id); if (!empty($categories)) { $out['cats'] = $categories[0]->term_id; } break; } return $out; } endif; // ショートコード属性を変更 add_filter('shortcode_atts_new_list', 'set_cats_from_category_or_post', 10, 4); add_filter('shortcode_atts_popular_list', 'set_cats_from_category_or_post', 10, 4); - ラベルCSSを追加
以下のコードをstyle.cssに追加します。
.widget-entry-cards.is-hidden { display: none !important; }
さいごに
今回紹介した方法を使えば、カテゴリーページや投稿ページで個別にカテゴリIDを指定する手間が省け、常に該当するカテゴリーの新着記事や人気記事をショートコードで簡単に自動表示できます。

