はじめに
Cocoon 2.8.0での見直しにより、ブロックがウィジェットと同様の独自カスタマイズを廃止し、WordPress標準の仕様に戻されました。
このため、以下のブロックではウィジェットと表示が異なります。
そこで対策として、ブロックを使用せず、独自のショートコードを使用して、ウィジェットを表示させます。
この記事では、この方法について説明します。
現状のブロック表示
- アーカイブ
- 2025-05 (58)
- 2025-04 (48)
- 2025-03 (24)
- 2025-02 (22)
- 2025-01 (24)
- 2024-12 (17)
- 2024-11 (55)
- 2024-10 (10)
- 2024-09 (8)
- 2024-08 (6)
- 2024-07 (10)
- 2024-06 (19)
- 2024-05 (17)
- 2024-04 (17)
- 2024-03 (15)
- 2024-02 (6)
- 2024-01 (2)
- 2023-12 (4)
- 2023-10 (1)
- 2023-09 (36)
- 2023-07 (26)
- 2023-06 (14)
- 2023-05 (10)
- カテゴリー
- Cocoonカスタマイズ集 (257)
- Cocoonマニュアル (46)
- スキンについて (104)
- プラグイン (4)
- リリースメモ (32)
- 雑談 (6)
- タグクラウド
Cocoonブロック (1) Cocoonマイクロコピー (1) Cocoon汎用ブロック (1) CSS (125) JavaScript (43) PHP (184) WordPress (91) クラシックエディター (1) スタイル (4) テキストブロック (1) ブロック (8) プラグイン (4) リッチテキスト (1)
完成イメージ
- アーカイブ
- カテゴリー
- タグクラウド
使用方法
以下にショートコードを示します。
[my_widget name="ウィジェット名" options='{"オプション名":値,...}']
ウィジェット名 | オプション | 説明 | 値 | 初期値 |
---|---|---|---|---|
WP_Widget_Archives | dropdown | ドロップダウンで表示 | 0=非表示 / 1=表示 | 0 |
count | 投稿数を表示 | 0=非表示 / 1=表示 | 0 | |
WP_Widget_Categories | dropdown | ドロップダウンで表示 | 0=非表示 / 1=表示 | 0 |
count | 投稿数を表示 | 0=非表示 / 1=表示 | 0 | |
hierarchical | 階層を表示 | 0=非表示 / 1=表示 | 0 | |
WP_Widget_Tag_Cloud | count | 投稿数を表示 | 0=非表示 / 1=表示 | 0 |
実装手順
以下のコードをfunctions.phpに追加します。
add_shortcode('my_widget', function($atts) {
$atts = shortcode_atts([
'name' => '',
'options' => '',
], $atts);
if (empty($atts['name'])) {
return '';
}
// 引数をデコード
$instance = !empty($atts['options']) ? json_decode($atts['options'], true) : [];
// タイトルを出力しない
$instance['title'] = '!';
// ウィジェット出力
ob_start();
the_widget($atts['name'], $instance);
$output = ob_get_clean();
// 特定のウィジェットに応じた処理
switch ($atts['name']) {
case 'WP_Widget_Categories':
case 'WP_Widget_Archives':
$output = remove_post_count_parentheses($output, $instance);
break;
case 'WP_Widget_Tag_Cloud':
$instance['show_count'] = isset($instance['count']) && $instance['count'] ? true : false;
$output = wp_tag_cloud_custom($output, $instance);
break;
}
return $output;
});
補足
今回、直接ウィジェットを呼び出すため、以下のようにショートコード用のウィジェットエリアを新たに設ける必要はありません。
以下の方法で、ウィジェットを直接呼び出すことができます。
[my_widget name="RecentCommentsWidgetItem"]
さいごに
今回紹介した方法を使えば、ショートコードを使用してウィジェットを表示することができます。
ウィジェット名とオプションをショートコードの引数として指定することで、カスタマイズされたウィジェットを記事やページに簡単に埋め込むことが可能です。