/*
Theme Name: STINGER8 Child
Template: stinger8
Version: 20170614
*/

/*media Queries タブレットサイズ（960px以下）
----------------------------------------------------*/
@media only screen and (max-width: 960x) {


/*-- ここまで --*/
}

/*media Queries タブレットサイズ（600px以上）
----------------------------------------------------*/
@media only screen and (min-width: 600px) {


/*-- ここまで --*/
}

/*media Queries PCサイズ（960px以上）
----------------------------------------------------*/
@media print, screen and (min-width: 960px) {


/*-- ここまで --*/
}
//記事上のウィジェット追加
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');