WordPressで自動挿入される【pタグ】や【brタグ】を自動挿入させない方法

WordPressには、投稿や固定ページで2行以上の改行を自動的にpタグに変換する機能(auto paragraph)や改行をbrタグに変換する機能が標準装備されています。この自動変換機能はそれほど気にはなりませんが、一方で特定の状況では不便に感じることもあります。
例えば、htmlコードなどを入力する際は、不要なpタグが挿入されることでレイアウトが崩れてしまうことがあります。また、デザインによってはpタグやbrタグの余分なスタイルが適用され、見た目が意図しないものになることもあります。
WordPressユーザーの中にはこの機能を停止させたいと考えている方も多いようです。停止にする方法はfunctions.phpにコードを追加するだけで、自動タグ変換機能を停止させることができます。この方法を使えば、サイト全体で停止にする事はもちろん、特定の投稿やページだけ停止にする事もできます。それでは用途に応じたコードをご説明します。

※functions.phpの編集には注意が必要です。変更を加える前に、バックアップを取ることを強くおすすめします。

サイト全体でp、brタグを自動挿入させない方法

以下のコードをfunctions.phpに記述します。このコードを記述することで、固定・投稿ページ共にp、brタグの自動挿入を停止します。

▼functions.phpに記述します

add_action('init', function() {
remove_filter('the_excerpt', 'wpautop');
remove_filter('the_content', 'wpautop');
});
add_filter('tiny_mce_before_init', function($init) {
$init['wpautop'] = false;
$init['apply_source_formatting'] = ture;
return $init;
});

固定ページのみp、brタグの自動挿入を停止

固定ページのみに対して、自動挿入されるp、brタグを停止しまう。投稿ページには適用させたくない場合に以下のコードをfunctions.phpに記述します。

▼functions.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;
}

投稿ページのみp、brタグの自動挿入を停止

投稿ページのみに対して、自動挿入されるp、brタグを停止しまう。固定ページには適用させたくない場合に以下のコードをfunctions.phpに記述します。

▼functions.phpに記述します

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;
}

特定の固定ページのみp、brタグの自動挿入を停止

例えば固定ページのIDが7の固定ページだけp、brタグの自動挿入を停止したい場合以下のような記述をします。
2行目if (is_page( array(7) ))の7の箇所に停止したい固定ページIDを記述します。

▼functions.phpに記述します

add_action( 'wp_head', function() {
if (is_page( array(7) )) {
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
}
});

複数の固定ページを指定する時は以下のように記述します。以下コードは固定ページのIDが7と10のページのみ自動挿入を停止しています。

▼functions.phpに記述します

add_action( 'wp_head', function() {
if (is_page( array('7','10') )) {
remove_filter('the_content', 'wpautop');
remove_filter('the_excerpt', 'wpautop');
}
});

まとめ

WordPressの自動タグ変換機能は、htmlの知識がない方や手軽にブログを書きたい方には便利ですが、Web制作を行う上では気になる点もありますね。好みに応じてコードを使い分けてみてはいかがでしょうか。

関連記事

TOP
TOP