デフォルトで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);
テキストエディタのみで無効化(ビジュアルエディタには影響なし)
テキストエディタ(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);