Функция use_block_editor_for_post_type()
в WordPress предназначена для определения, поддерживает ли определённый тип записи редактирование с использованием блокового редактора (Гутенберг). Это полезно, когда разработчик хочет контролировать, какие типы записей могут использовать блочный редактор, и когда нужно учитывать зависимости от REST API.
use_block_editor_for_post_type( string $post_type ): bool
- $post_type (обязательный) — строка, представляющая ярлык типа записи.
Возвращаемое значение
Функция возвращает true
, если тип записи может быть отредактирован с использованием блочного редактора, и false
, если он не поддерживает эту функциональность.
Описание работы функции
Редактор блоков зависит от REST API, поэтому если при регистрации типа записи параметр show_in_rest
установлен в false
, функция вернёт false
. Чтобы проверить поддержку блочного редактора для конкретного поста, рекомендуется использовать функцию use_block_editor_for_post()
.
Пример 1: Проверка поддержки блочного редактора для типа записи
$post_type = 'custom_post_type'; // Замените на ваш тип записи
if ( use_block_editor_for_post_type( $post_type ) ) {
echo "Тип записи поддерживает блочный редактор.";
} else {
echo "Тип записи не поддерживает блочный редактор.";
}
Этот пример демонстрирует, как можно использовать функцию для проверки, поддерживает ли определённый тип записи блочное редактирование.
Пример 2: Отключение редактора Gutenberg для всех типов записей
Если вы хотите отключить блочный редактор для всех типов записей, вы можете использовать фильтр use_block_editor_for_post_type
, как показано ниже:
add_filter( 'use_block_editor_for_post_type', '__return_false' );
Этот код отключает блочный редактор для всех типов записей, возвращая false
для каждого типа записи.
Пример 3: Включение редактора Gutenberg для определённых типов записей
Для того чтобы включить блочный редактор только для определённых типов записей, вы можете использовать следующий код:
function enable_gutenberg_editor_for_post_types( $current_status, $post_type ) {
// Определите массив типов записей, для которых Gutenberg должен быть включен
$enabled_post_types = array( 'post', 'page', 'custom_post_type' );
// Проверка, входит ли текущий тип записи в массив разрешенных
if ( in_array( $post_type, $enabled_post_types ) ) {
return true; // Включить Gutenberg
}
return $current_status; // Оставить текущий статус редактора
}
add_filter( 'use_block_editor_for_post_type', 'enable_gutenberg_editor_for_post_types', 10, 2 );
В этом примере мы создаем функцию, которая проверяет, входит ли текущий тип записи в массив разрешенных типов записей, и возвращает true
, если это так. Это позволяет гибко управлять тем, какие типы записей могут использовать блочный редактор.
Пример 4: Использование в плагине
Вот фрагмент кода из плагина Jetpack, который проверяет, может ли блочный редактор использоваться с заданным типом записи:
function can_edit_post_type( $post_type ) {
$can_edit = false;
if ( function_exists( 'gutenberg_can_edit_post_type' ) ) {
$can_edit = gutenberg_can_edit_post_type( $post_type );
} elseif ( function_exists( 'use_block_editor_for_post_type' ) ) {
$can_edit = use_block_editor_for_post_type( $post_type );
}
return $can_edit;
}
// Использование функции
$post_type = get_post_type( $post );
if ( $post_type && can_edit_post_type( $post_type ) ) {
remember_editor( $post->ID, 'block-editor' );
}
В этом примере функция can_edit_post_type()
проверяет, может ли блочный редактор редактировать данный тип записи, используя либо gutenberg_can_edit_post_type()
, либо use_block_editor_for_post_type()
. Эта проверка может быть использована в любом месте, где необходимо знать, доступен ли блочный редактор для определённого типа записи.
Заключение
Функция use_block_editor_for_post_type()
является важным инструментом для разработчиков, работающих с блоковым редактором WordPress. Она позволяет управлять тем, какие типы записей могут использовать блочный редактор, и помогает гарантировать, что редактор будет правильно функционировать в зависимости от настроек REST API.