<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/*****  メニューを切り替えたらコメントにしている部分も入れ替えること  ******/

function haup_add_ad_before_h2_for_3times($the_content) {
//1つ目の広告タグを挿入
if(isset( GetOP05_ana_ad()['first-autoad-content-use-js'] )){
	$use_js_first = GetOP05_ana_ad()['first-autoad-content-use-js'];
}else{
	$use_js_first = '';
}

if(isset(GetOP05_ana_ad()['first-autoad-content'])){
	if( $use_js_first == 1 ){
		$ad1 = GetOP05_ana_ad()['first-autoad-content'];
	}else{
		$ad1 = wp_kses_post(GetOP05_ana_ad()['first-autoad-content']);
	}
}

//2つ目の広告タグを挿入
if(isset( GetOP05_ana_ad()['second-autoad-content-use-js'] )){
	$use_js_second = GetOP05_ana_ad()['second-autoad-content-use-js'];
}else{
	$use_js_second = '';
}

if(isset(GetOP05_ana_ad()['second-autoad-content'])){
	if( $use_js_second == '1'){
		$ad2 = GetOP05_ana_ad()['second-autoad-content'];
	}else{
		$ad2 = wp_kses_post(GetOP05_ana_ad()['second-autoad-content']);
	}
}

//3つ目の広告タグを挿入
if(isset( GetOP05_ana_ad()['third-autoad-content-use-js'] )){
	$use_js_third = GetOP05_ana_ad()['third-autoad-content-use-js'];
}else{
	$use_js_third = '';
}

if(isset(GetOP05_ana_ad()['third-autoad-content'])){
if($use_js_third == '1'){
		$ad3 = GetOP05_ana_ad()['third-autoad-content'];
}	else{
		$ad3 = GetOP05_ana_ad()['third-autoad-content'];
	}
}

//20240302 投稿タイプフィルターへの対応
if ( haup_is_single_without_front() ) {//投稿と固定ページ
	$h2 = '/^<h2.*?>.+?<\/h2>$/im';//H2見出しのパターン
	if ( preg_match_all( $h2, $the_content, $h2s )) {//H2見出しが本文中にあるかどうか
		if ( $h2s[0] ) {//チェックは不要と思うけど一応
		
		if(isset($h2s[0][0])){
			if ( $h2s[0][0] ) {//1番目のH2見出し手前に広告を挿入
				if(isset( $ad1 )){
					$the_content  = str_replace($h2s[0][0], $ad1.$h2s[0][0], $the_content);
				}
			}
		}

		if(isset($h2s[0][1])){
			//if ( @$h2s[0][1] ) {//2番目のH2見出し手前に広告を挿入
			if ( $h2s[0][1] ) {//2番目のH2見出し手前に広告を挿入
				if(isset( $ad1 )){
					$the_content  = str_replace($h2s[0][1], $ad2.$h2s[0][1], $the_content);
				}
			}
		}

		if(isset($h2s[0][2])){
			//if ( @$h2s[0][2] ) {//2番目のH2見出し手前に広告を挿入
			if ( $h2s[0][2] ) {//3番目のH2見出し手前に広告を挿入
				if(isset( $ad1 )){
					$the_content  = str_replace($h2s[0][2], $ad3.$h2s[0][2], $the_content);
				}
			}
		}
	}
	}
}
	return $the_content;
}
add_filter('the_content','haup_add_ad_before_h2_for_3times');