アドセンス広告は「最初のh2上と記事下に表示させるのが効率がいい」と言われている。
記事下には簡単に入れられるが最初のh2上に差し込むのが少しややこしい。
↓つまりここに広告を入れる方法だ。
最初のh2上にアドセンス広告を表示させる方法
まずはfunctions.phpをいじるのでいつでも元に戻せるようにバックアップを取っておこう。functions.phpは少し間違うと画面が真っ白になるので更新するときいつもドキドキする。
最初のh2上にアドセンス広告を表示させる方法は、functions.phpに以下のコードをそのまま貼り付ける。
//------------------------------------------------------ // 広告差し込みウィジェットの追加 //------------------------------------------------------ //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' => __( '本文見出し上広告' ), 'id' => 'widget-in-article', 'before_widget' => '<div class="ttk-h2-before">', 'after_widget' => '</div>', 'before_title' => '', 'after_title' => '', ) );
ウィジェットエリアに項目が追加されていればOK
するとウィジェットの項目に「本文見出し上広告」というものが出てくる。
そこにアドセンスの広告を入れてcssを整えれば完成。