0
3807view

【WordPress】固定ページ、記事ページの自動Pタグ回避、imgのみも可能

WordPress自動Pタグ回避

WordPress初期状態では文字、画像に対して自動でPタグが付与されます。
Pタグ自動付与を固定ページのみ、記事ページのみ、img画像のみなどで振り分け適用する方法です。

固定ページ・記事ページ両方の自動pタグ回避

固定ページと記事ページ両方のpタグを一切なしでコーディングしたい人、または自分でpタグは入力するから自動で入力しないで欲しい時に使うコード。

function.phpに記述

remove_filter('the_content', 'wpautop');
remove_filter( 'the_excerpt', 'wpautop' );
the_contentは固定ページ、記事ページの本文に対して、the_excerptは抜粋を表示している場合にpタグを除去するもの。

固定ページのみ自動pタグ回避

固定ページは基本的に何度も書き直すページではなく、今後も増え続けるページではないことが多い為、固定ページのみpタグなしの設定が一番ポピュラー。

function.phpに記述

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;
}
array page とすることで固定ページに対してのpタグ回避のコードとなる

記事ページのみ自動pタグ回避

記事ページのみにpタグ回避をすることはあまりないが、一応使い方として記載

function.phpに記述

add_filter('the_content', 'wpautop_filter', 9);
function wpautop_filter($content) {
    global $post;
    $remove_filter = false;
 
    $arr_types = array('single'); //記事ページ
    $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;
}
array single とすることで記事ページに対してのpタグ回避のコードとなる

特定のページのみ自動pタグ回避

カテゴリに対して、または個別のページ、記事に対してpタグを回避する際に利用する

the_contentに記述

<? php the_content(); ?>

<? php remove_filter('the_content', 'wpautop'); ?>
<? php the_content(); ?>
カテゴリや記事のテンプレート the_content に対して使用する

img画像のみ自動pタグ回避

固定ページ、記事ページ共にpタグは自動で付与されるが、imgのみpタグの自動付与を回避する

function.phpに記述

function remove_p_on_images($content){
    return preg_replace('/<p>(\s*)(<img .* \/>)(\s*)<\/p>/iU', '\2', $content);
}
add_filter('the_content', 'remove_p_on_images');
pタグによってデザインが崩れる場合などに使用することができる
0

この記事が役に立ったらクリック!

0
役立つ情報メディア – MeteoLabo(メテオラボ)