ウィジェットを使って記事の最初の見出しの上にコンテンツを挿入する方法
WordPressでウィジェットを使って記事の最初の見出しの上にコンテンツを挿入する方法をメモ。
広告表示やCTAボタンの設置に便利です。
functions.php内に
register_sidebar( array( 'name' => __( '本文見出し上' ), 'id' => 'widget-in-article', 'before_widget' => '', 'after_widget' => '', 'before_title' => '', 'after_title' => '', ) ); define('H3_REG', '/<h3.*?>/i'); function get_h3_included_in_body( $the_content ){ if ( preg_match( H3_REG, $the_content, $h3results )) { return $h3results[0]; } } function add_widget_before_1st_h3($the_content) { if ( is_single() && is_active_sidebar( 'widget-in-article' ) ) { ob_start(); dynamic_sidebar( 'widget-in-article' ); $ad_template = ob_get_clean(); $h3result = get_h3_included_in_body( $the_content ); if ( $h3result ) { $count = 1; $the_content = preg_replace(H3_REG, $ad_template.$h3result, $the_content, 1); } } return $the_content; } add_filter('the_content','add_widget_before_1st_h3');
を記載。
あとは追加した「本文見出し上」というウィジェット内に追加するコンテンツを設置して完了。
最初の見出しがh2から始まる場合は
define('H3_REG', '/<h3.*?>/i');
の部分を
define('H3_REG', '/<h2.*?>/i');
に変更することでOK
WordPressのおすすめ参考書
bookfan 1号店 楽天市場店
¥3,300 (2024/03/26 18:51時点 | 楽天市場調べ)
ポチップ
ポチップ