【WordPress】超簡単!最初のh2上&本文下にウィジェットエリアを実装するコード

WordPressでブログを運営していると、アドセンスや広告など何かと挟みたくなる【最初のh2上】と【記事本文下】。この2か所にウィジェットエリアを実装しておくことで、簡単に変更の効くカスタマイズができる。
方法は驚くほど簡単で、以下のコードをfunctions.phpの一番下にコピペするだけでOK。※functions.phpを編集するときは必ずバックアップを!
最初のh2上と記事本文下にウィジェットエリアを実装するコード
// 最初のh2上にウィジェットを追加 ------------------------------------------
define('H2_REG', '/<h2.*?>/i');
function get_h2_included_in_body( $the_content ){
if ( preg_match( H2_REG, $the_content, $h2results )) {
return $h2results[0];
}
}
function add_widget_before_1st_h2($the_content) {
if ( is_single() &&
is_active_sidebar( 'widget-in-article' )
) {
ob_start();
dynamic_sidebar( 'widget-in-article' );
$ad_template = ob_get_clean();
$h2result = get_h2_included_in_body( $the_content );
if ( $h2result ) {
$count = 1;
$the_content = preg_replace(H2_REG, $ad_template.$h2result, $the_content, 1);
}
}
return $the_content;
}
add_filter('the_content','add_widget_before_1st_h2');
register_sidebar( array(
'name' => __( '最初のh2上' ),
'id' => 'widget-in-article',
'description' => '最初のh2上に表示されるウイジェット。',
'before_widget' => '<div class="before-h2">',
'after_widget' => '</div>',
'before_title' => '',
'after_title' => '',
) );
// 投稿本文下にウィジェットを追加 ------------------------------------------
register_sidebar(array(
'name' => '投稿本文下',
'id' => 'cta-widget',
'description' => '投稿本文下に表示されるウイジェット。',
'before_widget' => '<div class="cta-widget">',
'after_widget' => '</div>',
'before_title' => '',
'after_title' => '',
));
add_filter('the_content','my_content', 0);
function my_content($content){
if(!is_single()){
return $content;
}
$new_content = '';
$new_content .= $content;
$new_content .= get_dynamic_sidebar('投稿本文下');
return $new_content;
}
function get_dynamic_sidebar($index = 1){
$sidebar_contents = "";
ob_start();
dynamic_sidebar($index);
$sidebar_contents = ob_get_clean();
return $sidebar_contents;
}