はじめに
以下の質問に回答します。
「人気記事」を標準のデザインではなく、シンプルでスッキリとした「ランキング形式のリスト」として表示します。
使用方法
actionオプションを追加します。
[popular_list action="list"]
実装手順
以下のコードをfunctions.phpに追加します。
// ショートコード属性を変更
add_filter('shortcode_atts_popular_list', function ($out, $pairs, $atts) {
$GLOBALS['popular_list_action'] = $atts['action'] ?? null;
return $out;
}, 10, 3);
// テンプレート(人気記事カード)を変更
add_filter('cocoon_part__tmp/popular-card', function ($content, $name, $args) {
if (($GLOBALS['popular_list_action'] ?? '') === 'list') {
$post = $args['popular_post'];
return '<li><a href="' . get_permalink($post->ID) . '" class="popular-entry-card-link-list">' . esc_html($post->post_title) . '</a></li>';
}
return $content;
}, 10, 3);
// ショートコードHTML出力を変更
add_filter('do_shortcode_tag', function ($output, $tag, $attr) {
if ($tag !== 'popular_list') {
return $output;
}
// ランキング開始番号を算出
$start = isset($attr['offset']) ? intval($attr['offset']) + 1 : 1;
$rules = [
[
'search' => '/<div class="popular-entry-cards[^"]*"[^>]*>/',
'replace' => '<ol class="popular-entry-cards" start="' . $start . '">',
],
[
'search' => '/<\/div>(?=\s*<\/div>|\s*$)/',
'replace' => '</ol>',
],
];
// divコンテナをolリストへ変換
foreach ($rules as $rule) {
$output = preg_replace($rule['search'], $rule['replace'], $output);
}
// グローバル変数をリセット
$GLOBALS['popular_list_action'] = null;
return $output;
}, 10, 3);
参考:「新着記事」をリスト(ul)にカスタマイズする方法
「新着記事」も同様にリスト形式で表示可能です。
完成イメージ
使用方法
actionオプションを追加します。
[new_list action="list"]
実装手順
以下のコードをfunctions.phpに追加します。
// ショートコード属性を変更
add_filter('shortcode_atts_new_list', function ($out, $pairs, $atts) {
$GLOBALS['new_list_action'] = $atts['action'] ?? null;
return $out;
}, 10, 3);
// テンプレート(新着記事カード)を変更
add_filter('cocoon_part__tmp/widget-entry-card', function ($content, $name, $args) {
if (($GLOBALS['new_list_action'] ?? '') === 'list') {
$post_id = $args['post_id'];
$title = $args['title'];
return '<li><a href="' . get_permalink($post_id) . '" class="new-entry-card-link-list">' . esc_html($title) . '</a></li>';
}
return $content;
}, 10, 3);
// ショートコードHTML出力を変更
add_filter('do_shortcode_tag', function ($output, $tag, $attr) {
if ($tag !== 'new_list') {
return $output;
}
$rules = [
[
'search' => '/<div class="new-entry-cards[^"]*"[^>]*>/',
'replace' => '<ul class="new-entry-cards">',
],
[
'search' => '/<\/div>(?=\s*<\/div>|\s*$)/',
'replace' => '</ul>',
],
];
// divコンテナをulリストへ変換
foreach ($rules as $rule) {
$output = preg_replace($rule['search'], $rule['replace'], $output);
}
$GLOBALS['new_list_action'] = null;
return $output;
}, 10, 3);
さいごに
今回紹介した方法を使えば、「人気記事」ショートコードの利便性を損なうことなく、サイトの雰囲気に合わせたスッキリとしたランキング形式のリストを作成できます。
CSSを少し加えることで、オリジナリティのあるデザインにも調整可能です。


