函数文档

_block_template_render_without_post_block_context()

💡 云策文档标注

概述

此函数用于在渲染块模板时,从块上下文中移除与帖子相关的详细信息,以防止无限递归等问题。

关键要点

  • 函数 _block_template_render_without_post_block_context() 接收一个上下文数组作为参数,并返回过滤后的上下文。
  • 当上下文中的 postType 为 'wp_template' 时,函数会移除 postId 和 postType 键,以避免模板被误用为帖子上下文。
  • 此函数自 WordPress 5.8.0 版本引入,旨在确保块模板仅作为站点结构使用,而不干扰块如 Post Content 的正常渲染。

代码示例

function _block_template_render_without_post_block_context( $context ) {
    /*
     * When loading a template directly and not through a page that resolves it,
     * the top-level post ID and type context get set to that of the template.
     * Templates are just the structure of a site, and they should not be available
     * as post context because blocks like Post Content would recurse infinitely.
     */
    if ( isset( $context['postType'] ) && 'wp_template' === $context['postType'] ) {
        unset( $context['postId'] );
        unset( $context['postType'] );
    }

    return $context;
}

📄 原文内容

Removes post details from block context when rendering a block template.

Parameters

$contextarrayrequired
Default context.

Return

array Filtered context.

Source

function _block_template_render_without_post_block_context( $context ) {
	/*
	 * When loading a template directly and not through a page that resolves it,
	 * the top-level post ID and type context get set to that of the template.
	 * Templates are just the structure of a site, and they should not be available
	 * as post context because blocks like Post Content would recurse infinitely.
	 */
	if ( isset( $context['postType'] ) && 'wp_template' === $context['postType'] ) {
		unset( $context['postId'] );
		unset( $context['postType'] );
	}

	return $context;
}

Changelog

Version Description
5.8.0 Introduced.