ワードプレスのウィジェットを記事中に挿入して表示させる方法です。
まずは、サイドバーにウィジェットを登録。
次に、以下のコードをfunctions.phpに加えてください。
if( ! function_exists('insert_widget_to_content') ):
function insert_widget_to_content($content)
{
/**
* pタグで囲まれた最初の文の先頭にウィジェットを挿入
*/
return preg_replace_callback('/<p>(.*)<\/p>/', function($matches){
ob_start();
dynamic_sidebar(1); // サイドバーIDを指定
$widget = ob_get_contents(); // 指定したサイドバーのウィジェットを取得
ob_end_clean();
return "<p>{$widget}{$matches[1]}</p>";
}, $content, 1);
}
add_filter('the_content', 'insert_widget_to_content', 99, 1);
endif;
ちなみに、以下のように設定されている場合、上記のコードは正しく動作しません。
remove_filter('the_content', 'wpautop');
