WordPressにショートコードで挿入出来るウィジェットを作ろう!
これまた自分用に覚え書きです。
Wordpressの投稿・固定ページにショートコードで挿入出来るウィジェットを作る方法です。
function.phpに以下のコードを記載
function.phpを編集する際は十分ご注意ください。
必要なコードが消えてしまうとサイトが真っ白になる可能性もあります。
(その際の責任は負えません)
<?php ?>内に書いてください。
//カスタムウィジェットを作る
register_sidebar(array( 'name' => 'カスタムウィジェット', 'id' => 'widget_custom',
'before_widget' => '<div class="custom-widget">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widgettitle">',
'after_title' => '</h3>',
)
);
//カスタムウィジェットを呼び出すショートコードを作る
if ( !function_exists( 'widget_custom' ) ) {
function widget_custom() {
ob_start();
dynamic_sidebar( 'widget_custom' );
$osc = ob_get_clean();
return $osc;
}
add_shortcode( 'w_custom', 'widget_custom' );
}
完成!
これで、カスタムウィジェットとショートコードができました。

投稿中に
複数のカスタムウィジェットを作る場合は?
ちなみに複数のカスタムウィジェットとショートコードを作る場合はこんな感じです。
//カスタムウィジェットを作る
add_action(
'widgets_init',
function(){
register_sidebar(array(
'id' => 'widget_01',
'name' => 'ウィジェット1',
'before_widget' => '<div class="widget-01">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widgettitle">',
'after_title' => '</h3>',
));
register_sidebar(array(
'id' => 'widget_02',
'name' => 'ウィジェット2',
'before_widget' => '<div class="widget-02">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widgettitle">',
'after_title' => '</h3>',
));
register_sidebar(array(
'id' => 'widget_03',
'name' => 'ウィジェット3',
'before_widget' => '<div class="widget-03">',
'after_widget' => '</div>',
'before_title' => '<h3 class="widgettitle">',
'after_title' => '</h3>',
));
}
);
//カスタムウィジェットを呼び出すショートコードを作る
if ( !function_exists( 'widget_01' ) ) {
function widget_01() {
ob_start();
dynamic_sidebar( 'widget_01' );
$osc = ob_get_clean();
return $osc;
}
add_shortcode( 'w_custom01', 'widget_01' );
}
if ( !function_exists( 'widget_02' ) ) {
function widget_02() {
ob_start();
dynamic_sidebar( 'widget_02' );
$osc = ob_get_clean();
return $osc;
}
add_shortcode( 'w_custom02', 'widget_02' );
}
if ( !function_exists( 'widget_03' ) ) {
function widget_03() {
ob_start();
dynamic_sidebar( 'widget_03' );
$osc = ob_get_clean();
return $osc;
}
add_shortcode( 'w_custom03', 'widget_03' );
}
これで投稿中に[w_custom01][w_custom02][w_custom03]というショートコードを書くと、その部分にカスタムウィジェットが書き出されます!
なにかと便利なウィジェット機能を使い倒していきましょう。



