自動挿入されるpタグを削除

wordpress

すべての投稿に適用させる場合

remove_filter('the_content', 'wpautop'); // 記事の自動整形を無効にする
remove_filter('the_excerpt', 'wpautop'); // 抜粋の自動整形を無効にする

投稿ページのみに適用させる場合

add_filter('the_content', 'wpautop_filter', 9);
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;
}

固定ページのみに適用させる場合

add_filter('the_content', 'wpautop_filter', 9);
function wpautop_filter($content) {
global $post;
$remove_filter = false;
$arr_types = array('page'); //適用させる投稿タイプを指定
$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;
}

カスタム投稿ページのみに適用させる場合

add_filter('the_content', 'wpautop_filter', 9);
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;
}

複数の投稿タイプに適用させる場合

add_filter('the_content', 'wpautop_filter', 9);
function wpautop_filter($content) {
global $post;
$remove_filter = false;
$arr_types = array('投稿タイプ1', '投稿タイプ2', '投稿タイプ3'); //適用させる投稿タイプを指定
$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;
}

使用例
カスタム投稿ページには適用させず、投稿ページと固定ページのみに適用させたい場合は、以下のようなコードになります。

add_filter('the_content', 'wpautop_filter', 9);
function wpautop_filter($content) {
global $post;
$remove_filter = false;
$arr_types = array('post', 'page'); //適用させる投稿タイプを指定
$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;
}

場合によっては、固定ページごとにテンプレートが異なることもありますよね。すべての固定ページには適用させたくないけど、その中でも特定のテンプレートには適用させたい場合にはこちらの方法を使用してください

手順としては、まず適用させたいテンプレートファイルを開き、その中から下記のコードを探します。

<?php the_content(); ?>

上記のコードを見つけたら、その直前に下記のコードをコピペしてください。

<?php remove_filter('the_content', 'wpautop'); ?>

以下のような状態にし、あとは保存して適用させればOKです。

<?php remove_filter('the_content', 'wpautop'); ?>
<?php the_content(); ?>