Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaoru-fukusato/a6e3f83c5bea1ff8ddc9923de0163a21 to your computer and use it in GitHub Desktop.
Save kaoru-fukusato/a6e3f83c5bea1ff8ddc9923de0163a21 to your computer and use it in GitHub Desktop.
本文中にウィジェットを作成する
///////////////////////////////////////
// 投稿本文中ウィジェットの追加
///////////////////////////////////////
register_sidebars(1,
array(
'name'=>'投稿本文中',
'id' => 'widget-in-article',
'description' => '投稿本文中に表示されるウィジェット。文中最初のH2タグの手前に表示されます。',
'before_widget' => '<div id="%1$s" class="widget-in-article %2$s">',
'after_widget' => '</div>',
'before_title' => '<div class="widget-in-article-title">',
'after_title' => '</div>',
));
///////////////////////////////////////
//H2見出しを判別する正規表現を定数にする
///////////////////////////////////////
define('H2_REG', '/<h2.*?>/i');//H2見出しのパターン
///////////////////////////////////////
//本文中にH2見出しが最初に含まれている箇所を返す(含まれない場合はnullを返す)
//H3-H6しか使っていない場合は、h2部分を変更してください
///////////////////////////////////////
function get_h2_included_in_body( $the_content ){
if ( preg_match( H2_REG, $the_content, $h2results )) {//H2見出しが本文中にあるかどうか
return $h2results[0];
}
}
///////////////////////////////////////
// 投稿本文中の最初のH2見出し手前にウィジェットを追加する処理
///////////////////////////////////////
function add_widget_before_1st_h2($the_content) {
if ( is_single() && //投稿ページのとき、固定ページも表示する場合はis_singular()にする
is_active_sidebar( 'widget-in-article' ) //ウィジェットが設定されているとき
) {
//広告(AdSense)タグを記入
ob_start();//バッファリング
dynamic_sidebar( 'widget-in-article' );//本文中ウィジェットの表示
$ad_template = ob_get_clean();
$h2result = get_h2_included_in_body( $the_content );//本文にH2タグが含まれていれば取得
if ( $h2result ) {//H2見出しが本文中にある場合のみ
//最初のH2の手前に広告を挿入(最初のH2を置換)
$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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment