函数文档

_register_theme_block_patterns()

💡 云策文档标注

概述

_register_theme_block_patterns() 函数用于注册活动主题在 ./patterns/ 目录下提供的块模式。它处理主题和父主题的模式注册,并包含错误检查和国际化支持。

关键要点

  • 函数在主题引导过程中运行,如果无有效活动主题则提前退出以避免错误。
  • 支持子主题覆盖父主题中相同 slug 的块模式。
  • 使用 WP_Block_Patterns_Registry 检查模式是否已注册,避免重复。
  • 包含文件存在性验证,缺失文件时会触发 _doing_it_wrong() 警告并清除缓存。
  • 自动翻译模式标题和描述,使用 translate_with_gettext_context() 函数。
  • 最终通过 register_block_pattern() 注册每个块模式。

代码示例

if ( empty( wp_get_active_and_valid_themes() ) ) {
    return;
}
$themes   = array();
$theme    = wp_get_theme();
$themes[] = $theme;
if ( $theme->parent() ) {
    $themes[] = $theme->parent();
}
$registry = WP_Block_Patterns_Registry::get_instance();
foreach ( $themes as $theme ) {
    $patterns    = $theme->get_block_patterns();
    $dirpath     = $theme->get_stylesheet_directory() . '/patterns/';
    $text_domain = $theme->get( 'TextDomain' );
    foreach ( $patterns as $file => $pattern_data ) {
        if ( $registry->is_registered( $pattern_data['slug'] ) ) {
            continue;
        }
        $file_path = $dirpath . $file;
        if ( ! file_exists( $file_path ) ) {
            _doing_it_wrong(
                __FUNCTION__,
                sprintf(
                    __( 'Could not register file "%s" as a block pattern as the file does not exist.' ),
                    $file
                ),
                '6.4.0'
            );
            $theme->delete_pattern_cache();
            continue;
        }
        $pattern_data['filePath'] = $file_path;
        $pattern_data['title'] = translate_with_gettext_context( $pattern_data['title'], 'Pattern title', $text_domain );
        if ( ! empty( $pattern_data['description'] ) ) {
            $pattern_data['description'] = translate_with_gettext_context( $pattern_data['description'], 'Pattern description', $text_domain );
        }
        register_block_pattern( $pattern_data['slug'], $pattern_data );
    }
}

注意事项

  • 函数依赖于主题的 functions.php 文件加载,确保主题有效以避免运行时错误。
  • 模式文件必须位于主题的 ./patterns/ 目录下,否则注册会失败并触发警告。
  • 翻译使用主题的 TextDomain,确保国际化设置正确。
  • 从 WordPress 6.0.0 版本引入,后续版本有更新如添加 postTypes 和 templateTypes 属性。

📄 原文内容

Register any patterns that the active theme may provide under its ./patterns/ directory.

Source

function _register_theme_block_patterns() {

	/*
	 * During the bootstrap process, a check for active and valid themes is run.
	 * If no themes are returned, the theme's functions.php file will not be loaded,
	 * which can lead to errors if patterns expect some variables or constants to
	 * already be set at this point, so bail early if that is the case.
	 */
	if ( empty( wp_get_active_and_valid_themes() ) ) {
		return;
	}

	/*
	 * Register patterns for the active theme. If the theme is a child theme,
	 * let it override any patterns from the parent theme that shares the same slug.
	 */
	$themes   = array();
	$theme    = wp_get_theme();
	$themes[] = $theme;
	if ( $theme->parent() ) {
		$themes[] = $theme->parent();
	}
	$registry = WP_Block_Patterns_Registry::get_instance();

	foreach ( $themes as $theme ) {
		$patterns    = $theme->get_block_patterns();
		$dirpath     = $theme->get_stylesheet_directory() . '/patterns/';
		$text_domain = $theme->get( 'TextDomain' );

		foreach ( $patterns as $file => $pattern_data ) {
			if ( $registry->is_registered( $pattern_data['slug'] ) ) {
				continue;
			}

			$file_path = $dirpath . $file;

			if ( ! file_exists( $file_path ) ) {
				_doing_it_wrong(
					__FUNCTION__,
					sprintf(
						/* translators: %s: file name. */
						__( 'Could not register file "%s" as a block pattern as the file does not exist.' ),
						$file
					),
					'6.4.0'
				);
				$theme->delete_pattern_cache();
				continue;
			}

			$pattern_data['filePath'] = $file_path;

			// Translate the pattern metadata.
			// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.LowLevelTranslationFunction
			$pattern_data['title'] = translate_with_gettext_context( $pattern_data['title'], 'Pattern title', $text_domain );
			if ( ! empty( $pattern_data['description'] ) ) {
				// phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.LowLevelTranslationFunction
				$pattern_data['description'] = translate_with_gettext_context( $pattern_data['description'], 'Pattern description', $text_domain );
			}

			register_block_pattern( $pattern_data['slug'], $pattern_data );
		}
	}
}

Changelog

Version Description
6.4.0 Uses the WP_Theme::get_block_patterns method.
6.2.0 The templateTypes property was added.
6.1.0 The postTypes property was added.
6.0.0 Introduced.