【ワードプレス】記事の先頭にウィジェットを挿入する方法
ワードプレスのウィジェットを記事中に挿入して表示させる方法です。
まずは、サイドバーにウィジェットを登録。
次に、以下のコードをfunctions.phpに加えてください。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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; |
ちなみに、以下のように設定されている場合、上記のコードは正しく動作しません。
1 | remove_filter('the_content', 'wpautop'); |
コメントを投稿するにはログインが必要です。