You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为WordPress区块图案添加分类?现有代码问题求助

为WordPress区块图案关联自定义分类的问题

我已完成以下操作:给wp_block文章类型注册了自定义分类,并且基于该分类的术语成功创建了区块图案分类。但在尝试将wp_block文章关联到对应区块图案时,遇到了分类和内容无法正确添加的问题。

已完成的代码(自定义分类与区块分类创建)

// Custom taxonomy for wp_block post type
function register_patterns_taxonomy() {
    $labels = array(
        'name' => 'Pattern category',
        'singular_name' => 'Pattern category',
        'search_items' => 'Search Patterns categories',
        'all_items' => 'All Patterns categories',
        'parent_item' => 'Parent Pattern category',
        'parent_item_colon' => 'Parent Pattern category:',
        'edit_item' => 'Edit Pattern category',
        'update_item' => 'Update Pattern category',
        'add_new_item' => 'Add New Pattern category',
        'new_item_name' => 'New Pattern category Name',
        'menu_name' => 'Patterns categories',
    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'public' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'show_in_rest' => true,
        'rewrite' => array( 'slug' => 'patterns_categories' ),
    );

    register_taxonomy( 'patterns_categories', array( 'wp_block' ), $args );
}
add_action( 'init', 'register_patterns_taxonomy' );

// creating patters categories by taxonomy terms
function create_block_pattern_category_for_terms() {
    $taxonomy = 'patterns_categories';
    $terms = get_terms( array(
        'taxonomy' => $taxonomy,
        'hide_empty' => false, // 获取所有术语,包括空的
    ) );

    foreach ( $terms as $term ) {
        register_block_pattern_category(
            $term->slug,
            array( 'label' => __( $term->name, 'wpdocs-my-plugin' ) )
        );
    }
}
add_action( 'init', 'create_block_pattern_category_for_terms' );

尝试的代码(关联区块图案与分类)

// trying to create patterns
$args = array(
    'post_type' => 'wp_block',
    'posts_per_page' => -1,
);

$posts = get_posts($args);

foreach ($posts as $post) {
    setup_postdata($post);

    $title = get_the_title();
    $content = get_the_content();

    // Fetch terms associated with this post
    $terms = wp_get_post_terms($post->ID, 'patterns_categories', array('fields' => 'slugs'));

    // Create block pattern
    register_block_pattern(
        'handy-options/' . $title,
        array(
            'title'       => $title,
            'description' => _x('Two horizontal buttons, the left button is filled in, and the right button is outlined.', 'Block pattern description', 'theme-slug'),
            'categories'  => $terms,
            'content'     => wp_json_encode($content),
        )
    );
}
wp_reset_postdata(); 

问题分析与修正方案

核心问题点

  1. 区块ID不合法:直接使用文章标题作为ID的一部分,标题含特殊字符时会导致图案注册失败。
  2. 内容格式错误:wp_json_encode($content)会把区块标记转义成JSON字符串,而register_block_pattern需要的是原始的区块HTML标记。
  3. 钩子时机不对:代码直接运行,没有绑定到合适的钩子,可能在分类注册完成前执行,导致分类关联失败。
  4. 重复注册风险:每次初始化都会重复注册图案,引发PHP警告。

修正后的完整代码

function register_wp_block_as_patterns() {
    // 确保wp_block文章类型存在
    if ( ! post_type_exists('wp_block') ) {
        return;
    }

    $args = array(
        'post_type' => 'wp_block',
        'posts_per_page' => -1,
        'post_status' => 'publish', // 仅处理已发布的区块
    );

    $posts = get_posts($args);

    foreach ($posts as $post) {
        // 使用文章ID确保图案ID唯一且合法
        $pattern_id = 'handy-options/pattern-' . $post->ID;
        
        // 检查图案是否已注册,避免重复
        if ( WP_Block_Patterns_Registry::get_instance()->is_registered( $pattern_id ) ) {
            continue;
        }

        $title = get_the_title($post->ID);
        // 获取原始区块内容,无需转义
        $content = get_post_field('post_content', $post->ID);

        // 获取关联的分类术语slug
        $terms = wp_get_post_terms($post->ID, 'patterns_categories', array('fields' => 'slugs'));
        // 处理无分类的情况,设置默认分类
        $categories = empty($terms) ? ['uncategorized'] : $terms;

        // 注册区块图案
        register_block_pattern(
            $pattern_id,
            array(
                'title'       => $title,
                'description' => get_post_field('post_excerpt', $post->ID) ?: _x('自定义区块图案', 'Block pattern description', 'theme-slug'),
                'categories'  => $categories,
                'content'     => $content,
            )
        );
    }
}
// 设置较高优先级,确保在分类注册完成后执行
add_action('init', 'register_wp_block_as_patterns', 100);

关键修改说明

  • 唯一ID生成:用文章ID作为图案ID的一部分,彻底避免特殊字符问题,保证每个图案ID唯一。
  • 内容正确传递:直接读取post_content字段,该字段存储的正是register_block_pattern所需的原始区块标记,无需额外编码。
  • 分类容错处理:当文章无关联分类时,自动使用默认分类,避免分类数组为空导致的错误。
  • 钩子时机优化:绑定到init钩子并设置优先级100,确保自定义分类和区块分类都已注册完成后再执行图案注册。
  • 重复注册防护:通过区块图案注册表检查是否已注册,避免重复操作引发警告。

内容的提问来源于stack exchange,提问作者D_P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 22:48:08