函数文档

use_block_editor_for_post()

💡 云策文档标注

概述

use_block_editor_for_post() 函数用于判断指定文章是否可以在块编辑器中编辑。它接受文章 ID 或 WP_Post 对象作为参数,返回布尔值,并可通过过滤器进行自定义。

关键要点

  • 函数接受 $post 参数,可以是整数(文章 ID)或 WP_Post 对象,用于指定要检查的文章。
  • 返回布尔值,表示文章是否可在块编辑器中编辑。
  • 内部首先通过 get_post() 获取文章对象,如果无效则返回 false。
  • 在管理界面且存在 meta-box-loader 参数时,返回 false 以避免在元框加载器中使用块编辑器。
  • 核心逻辑调用 use_block_editor_for_post_type() 检查文章类型是否支持块编辑器。
  • 提供 'use_block_editor_for_post' 过滤器,允许开发者自定义判断逻辑。

代码示例

function use_block_editor_for_post( $post ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	// We're in the meta box loader, so don't use the block editor.
	if ( is_admin() && isset( $_GET['meta-box-loader'] ) ) {
		check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
		return false;
	}

	$use_block_editor = use_block_editor_for_post_type( $post->post_type );

	/**
	 * Filters whether a post is able to be edited in the block editor.
	 *
	 * @since 5.0.0
	 *
	 * @param bool    $use_block_editor Whether the post can be edited or not.
	 * @param WP_Post $post             The post being checked.
	 */
	return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
}

注意事项

  • 函数在 WordPress 6.1.0 版本中从 wp-admin 移至 wp-includes,开发者需注意兼容性。
  • 使用前应确保文章对象有效,否则可能返回 false。
  • 过滤器 'use_block_editor_for_post' 可用于扩展或修改默认行为,适用于高级定制场景。

📄 原文内容

Returns whether the post can be edited in the block editor.

Parameters

$postint|WP_Postrequired
Post ID or WP_Post object.

Return

bool Whether the post can be edited in the block editor.

Source

function use_block_editor_for_post( $post ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	// We're in the meta box loader, so don't use the block editor.
	if ( is_admin() && isset( $_GET['meta-box-loader'] ) ) {
		check_admin_referer( 'meta-box-loader', 'meta-box-loader-nonce' );
		return false;
	}

	$use_block_editor = use_block_editor_for_post_type( $post->post_type );

	/**
	 * Filters whether a post is able to be edited in the block editor.
	 *
	 * @since 5.0.0
	 *
	 * @param bool    $use_block_editor Whether the post can be edited or not.
	 * @param WP_Post $post             The post being checked.
	 */
	return apply_filters( 'use_block_editor_for_post', $use_block_editor, $post );
}

Hooks

apply_filters( ‘use_block_editor_for_post’, bool $use_block_editor, WP_Post $post )

Filters whether a post is able to be edited in the block editor.

Changelog

Version Description
6.1.0 Moved to wp-includes from wp-admin.
5.0.0 Introduced.