WordPress
このポートフォリオ作成で、ググった内容をまとめていく備忘録シリーズ(勝手にシリーズ化)。
指定されたテキストに含まれる 2 連続の改行を HTML のパラグラフへ置き換えます(<p>...</p>)。
WordPress はこの関数を投稿や固定ページの本文と抜粋のフィルターに使用します。(Codex日本語版)
サイト全体の抜粋や記事でpタグを勝手に挿入しないようにするには、以下のコードをfunctions,phpに追記します。
remove_filter('the_excerpt', 'wpautop');
remove_filter('the_content', 'wpautop');remove_filterの説明はこちら。第1引数に対象となるフィルターフック、第2引数にコールバック関数を入れます。(第3もあるけどオプションなので省略)
投稿ページだけに適用するには、こちらを追記します。
add_filter('the_content', 'wpautop_filter'); //上述のremove_filterの逆ですね
function wpautop_filter($content) {
global $post;
$remove_filter = false;
$arr_types = array('post'); //適用させる投稿タイプを指定
$post_type = get_post_type( $post->ID );
if (in_array($post_type, $arr_types)) $remove_filter = true;
if ( $remove_filter ) {
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
}
return $content;
}
固定ページの場合には、投稿ページのコードの5行目(太字の部分)を、以下のように代えて全体をfunctios.phpに書き込みます
$arr_types = array('page');
デフォルトの投稿ページや固定ページはそのままに、カスタム投稿タイプのページだけpタグが入らないようにするには、こちらを書き込みます。
add_filter('the_content', 'wpautop_filter');
function wpautop_filter($content) {
global $post;
$remove_filter = false;
$arr_types = array('カスタム投稿タイプを入力');
$post_type = get_post_type( $post->ID );
if (in_array($post_type, $arr_types)) $remove_filter = true;
if ( $remove_filter ) {
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
}
return $content;
}
以上です。