WordPressの自動的に付与される<p>や<br>を無効にしたい

デフォルトでWordPressは、wpautop という関数が自動的に<p>や<br>タグを付与する仕組みになっています。
Webサイトの更新をタグを理解している従業員や専門業者に全て任せているスタンスなら問題ありませんが、顧客・取引先(以下クライアント)側での発信(イレギュラーな休業や急を要する内容)が必要な場合に意外とよくある出来事なのです。
だから特定のユーザー権限ごとに wpautop を無効にする方法が必要になります。

WordPressのログインユーザーの種類と名前は以下になります。
特別な理由が無ければクライアントには「editor」でのアカウントを。制作側は「administrator」で進めていきます。
[購読者]subscriber
[寄稿者]contributor
[投稿者]author
[編集者]editor
[管理者]administrator

functions.php でユーザー権限ごとに wpautop を無効にする

functions.php に以下のコードを追加すると、特定のユーザー権限に対して<p>や<br>の自動挿入を無効化できます。

function disable_wpautop_for_specific_roles($content) {
    // 現在のユーザー情報を取得
    $user = wp_get_current_user();
    
    // 無効化したいユーザー権限(管理者)
    $disabled_roles = array('administrator');

    // ユーザーが指定された権限を持っている場合、wpautop を無効化
    if (array_intersect($disabled_roles, $user->roles)) {
        remove_filter('the_content', 'wpautop');
        remove_filter('the_excerpt', 'wpautop');
    }
    
    return $content;
}
add_filter('the_content', 'disable_wpautop_for_specific_roles', 9);
add_filter('the_excerpt', 'disable_wpautop_for_specific_roles', 9);
wp_get_current_user() → 現在のログインユーザーの情報を取得
$disabled_roles = array(‘administrator’); → 管理者のみに適用(編集者のみの場合は「editor」を置き換える)
array_intersect($disabled_roles, $user->roles) → ユーザーの権限がリストに含まれているかチェック
remove_filter(‘the_content’, ‘wpautop’); → 本文の<p>&<br>の自動挿入を無効化
remove_filter(‘the_excerpt’, ‘wpautop’); → 抜粋部分の<p>&<br>の自動挿入を無効化

テキストエディタのみで無効化(ビジュアルエディタには影響なし)

テキストエディタ(HTMLモード) だけで<p>や<br>を無効にしたい場合は、以下のコードを functions.php に追加します。

function disable_wpautop_for_text_editor($content) {
    if (wp_doing_ajax() || is_admin()) {
        return $content;
    }
    
    // ユーザー権限をチェック(例: "administrator" のみ無効化)
    $user = wp_get_current_user();
    if (in_array('administrator', $user->roles)) {
        remove_filter('the_content', 'wpautop');
        remove_filter('the_excerpt', 'wpautop');
    }
    
    return $content;
}
add_filter('the_content', 'disable_wpautop_for_text_editor', 9);

まとめ

wpautop の自動挿入を、ユーザー権限ごとに無効化するには functions.php で remove_filter() を適用!
管理者や編集者など、特定の権限だけに適用できる。
ビジュアルエディタの動作には影響しないように設定可能。

上部へスクロール