はじめに
Cocoonでは、Gutenbergエディターまたはクラシックエディターのどちらを使用するかを設定できます。
ただし、一度設定したエディターは全ての投稿に適用され、プラグイン「Classic Editor」のように投稿ごとに自由に切り替えることはできません。
過去にクラシックエディターで作成した投稿を、そのままクラシックエディターで編集したい場合もあるでしょう。
そこで、クラシックエディターで作成した投稿は自動でGutenbergエディターから切り替わるようにします。
この記事では、この方法について説明します。
実装手順
以下の手順で実装します。
- ラベルCocoon設定
表1に示す項目を設定をします。
Cocoon設定 設定 大項目 項目 設定値 エディター エディター共通設定 Gutenbergエディターを有効にする オン - ラベルPHPを追加
以下のコードをfunctions.phpに追加します。
add_filter('use_block_editor_for_post', function ($use_block_editor, $post) { // 新規投稿は除外 if ($post->post_status === 'auto-draft') { return $use_block_editor; } $content = get_post_field('post_content', $post->ID); // ブロックを含まない投稿はクラシックエディターに切り替え if (strpos($content, 'wp:') === false) { // Gutenbergエディターを無効化 return false; } return $use_block_editor; }, 10, 2);
参考:投稿ごとにクラシックエディタを選択できるメタボックスを追加する方法
プラグイン「Classic Editor」のように、投稿ごとにGutenbergエディターとクラシックエディターを切り替えられるようにします。
完成イメージ

実装手順
以下の手順で実装します。
- ラベルCocoon設定
表1に示す項目を設定をします。
Cocoon設定 設定 大項目 項目 設定値 エディター Gutenberg Gutenbergエディターを有効にする オン - ラベルPHPを追加
以下のコードをfunctions.phpに追加します。
// メタボックスを追加 add_action('add_meta_boxes', function () { add_meta_box( 'editor_selection', 'エディター設定', 'render_editor_selection', 'post', 'side', 'default' ); }); /** * メタボックスの入力フォームを出力 * * @param WP_Post $post 現在の投稿オブジェクト * @return void */ if (!function_exists('render_editor_selection')): function render_editor_selection($post) { // 現在の設定を取得 $use_classic_editor = get_post_meta($post->ID, 'my_use_classic_editor', true); ?> <?php wp_nonce_field('editor_selection_action', 'editor_selection_nonce'); ?> <input type="checkbox" name="use_classic_editor" id="use_classic_editor" value="1" <?php checked($use_classic_editor, '1'); ?> /> クラシックエディターを使用 <?php } endif; // 投稿データを保存 add_action('save_post', function ($post_id) { // nonceチェック if (!isset($_POST['editor_selection_nonce']) || !wp_verify_nonce($_POST['editor_selection_nonce'], 'editor_selection_action')) { return; } // 自動保存チェック if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return; } // リビジョン除外チェック if (wp_is_post_revision($post_id)) { return; } // 権限チェック if (!current_user_can('edit_post', $post_id)) { return; } if (isset($_POST['use_classic_editor'])) { update_post_meta($post_id, 'my_use_classic_editor', '1'); } else { delete_post_meta($post_id, 'my_use_classic_editor'); } }); // クラシックエディターに切り替え add_filter('use_block_editor_for_post', function ($use_block_editor, $post) { // 設定を取得 $use_classic_editor = get_post_meta($post->ID, 'my_use_classic_editor', true); // Gutenbergエディターを無効化 if ($use_classic_editor === '1') { return false; } return $use_block_editor; }, 10, 2);
さいごに
今回紹介した方法を使えば、過去にクラシックエディターで作成した投稿を自動でGutenbergエディターから切り替えることができます。
Gutenbergとクラシックエディターを併用したい場合に、ぜひ活用してください。


