商业与职场

WooCommerce结账扩展

为区块版购物车或结账页添加促销组件、自定义字段和步骤,并通过 Store API 保存结账数据。

# WooCommerce Blocks

## 概述

WooCommerce Blocks 用基于 React 的 Gutenberg 区块取代了传统的短代码购物车和结账页面。自定义插件可以通过注册内部区块(结账步骤中的自定义字段)、使用 SlotFills(向预定义的注入点注入 UI)以及扩展 Store API 来保存和读取自定义数据,从而扩展结账区块。自 8.3 版本起,基于区块的结账页面成为新 WooCommerce 商店的默认配置。

## 何时使用此 Skill

- 为结账表单添加自定义字段时(礼物留言、配送日期选择器、VAT 税号)
- 向购物车或结账区块注入促销内容或追加销售横幅时
- 创建带有额外业务逻辑的自定义结账步骤时
- 在现有 WooCommerce 网站上替换旧版短代码结账页面时
- 构建无需修改核心模板即可扩展结账行为的插件时

## 核心指令

1. **注册结账内部区块**

   内部区块是在结账步骤中渲染的 React 组件。它们需要 PHP 区块注册 + JS/React 前端:

   ```php
   <?php
   // my-checkout-fields/my-checkout-fields.php
   add_action('woocommerce_blocks_loaded', function () {
       if (!class_exists('Automattic\WooCommerce\Blocks\Integrations\IntegrationInterface')) {
           return;
       }
       require_once __DIR__ . '/class-my-checkout-integration.php';
       add_action(
           'woocommerce_blocks_checkout_block_registration',
           function ($integration_registry) {
               $integration_registry->register(new My_Checkout_Integration());
           }
       );
   });
   ```

   ```php
   <?php
   // class-my-checkout-integration.php
   use Automattic\WooCommerce\Blocks\Integrations\IntegrationInterface;

   class My_Checkout_Integration implements IntegrationInterface {
       public function get_name() {
           return 'my-checkout-fields';
       }

       public function initialize() {
           $this->register_block_frontend_scripts();
           $this->register_inner_block();
       }

       private function register_block_frontend_scripts() {
           wp_register_script(
               'my-checkout-fields-frontend',
               plugin_dir_url(__FILE__) . 'build/frontend.js',
               ['wc-blocks-checkout', 'wp-element'],
               filemtime(plugin_dir_path(__FILE__) . 'build/frontend.js'),
               true
           );
       }

       private function register_inner_block() {
           register_block_type(plugin_dir_path(__FILE__) . 'build/blocks/gift-message/block.json');
       }

       public function get_script_handles() {
           return ['my-checkout-fields-frontend'];
       }

       public function get_editor_script_handles() {
           return [];
       }

       public function get_script_data() {
           return [];
       }
   }
   ```

2. **创建内部区块 React 组件**

   ```javascript
   // src/blocks/gift-message/index.js
   import { registerCheckoutBlock } from "@woocommerce/blocks-checkout";
   import { __ } from "@wordpress/i18n";
   import { useEffect, useState } from "@wordpress/element";
   import {
     useExtensionCartUpdateData,
     extensionCartUpdate,
   } from "@woocommerce/blocks-checkout";

   const Block = ({ children, checkoutExtensionData }) => {
     const [giftMessage, setGiftMessage] = useState("");

     // Persist gift message to cart extension data
     const handleChange = (e) => {
       const value = e.target.value;
       setGiftMessage(value);
       extensionCartUpdate({
         namespace: "my-checkout-fields",
         data: { gift_message: value },
       });
     };

     return (

         <label htmlFor="gift-message">
           {__("Gift message (optional)", "my-checkout-fields")}
         </label>
         <textarea
           id="gift-message"
           value={giftMessage}
           onChange={handleChange}
           placeholder={__("Write your message here...", "my-checkout-fields")}
           rows={3}
           maxLength={200}
         />
         {giftMessage.length}/200

     );
   };

   registerCheckoutBlock({
     metadata: {
       name: "my-checkout-fields/gift-message",
       title: "Gift Message",
       category: "woocommerce",
       parent: ["woocommerce/checkout-shipping-methods-block"],
       attributes: {},
     },
     component: Block,
   });
   ```

3. **扩展 Store API 以持久保存自定义数据**

   ```php
   <?php
   // Extend the Store API Cart schema to accept and store custom extension data
   add_action('woocommerce_blocks_loaded', function () {
       woocommerce_store_api_register_endpoint_data([
           'endpoint'        => Automattic\WooCommerce\StoreApi\Schemas\V1\CartSchema::IDENTIFIER,
           'namespace'       => 'my-checkout-fields',
           'schema_callback' => function () {
               return [
                   'gift_message' => [
                       'description' => 'Gift message for the order',
                       'type'        => 'string',
                       'context'     => ['view', 'edit'],
                       'readonly'    => false,
                       'sanitize_callback' => 'sanitize_textarea_field',
                   ],
               ];
           },
           'schema_type' => ARRAY_A,
       ]);

       // Save the gift message to WC session when cart is updated
       woocommerce_store_api_register_update_callback([
           'namespace' => 'my-checkout-fields',
           'callback'  => function (array $data) {
               if (isset($data['gift_message'])) {
                   WC()->session->set('gift_message', sanitize_textarea_field($data['gift_message']));
               }
           },
       ]);
   });

   // Transfer session data to order meta on checkout
   add_action('woocommerce_checkout_order_created', function ($order) {
       $gift_message = WC()->session->get('gift_message', '');
       if (!empty($gift_message)) {
           $order->update_meta_data('_gift_message', $gift_message);
           $order->save();
       }
   });
   ```

4. **使用 SlotFills 注入 UI,无需内部区块**

   SlotFills 比内部区块更简单 — 它们将内容注入预定义的插槽:

   ```javascript
   // src/frontend.js
   import { registerPlugin } from "@wordpress/plugins";
   import { ExperimentalOrderMeta } from "@woocommerce/blocks-checkout";
   import { __ } from "@wordpress/i18n";
   import { useSelect } from "@wordpress/data";
   import { CART_STORE_KEY } from "@woocommerce/block-data";

   const CartUpsellBanner = () => {
     const cartTotal = useSelect((select) => {
       const cart = select(CART_STORE_KEY).getCartData();
       return cart?.totals?.total_items;
     });

     const freeShippingThreshold = 5000; // $50.00 in cents
     const remaining = freeShippingThreshold - parseInt(cartTotal ?? "0");

     if (remaining <= 0) return null;

     return (

         {__(`Add $${(remaining / 100).toFixed(2)} more for free shipping!`, "my-checkout-fields")}

     );
   };

   registerPlugin("my-cart-upsell", {
     render: () => (
       <ExperimentalOrderMeta>
         <CartUpsellBanner />
       </ExperimentalOrderMeta>
     ),
     scope: "woocommerce-checkout",
   });
   ```

5. **使用 `@wordpress/scripts` 构建资源并将其加入加载队列**

   ```json
   // package.json
   {
     "scripts": {
       "build": "wp-scripts build src/frontend.js src/blocks/gift-message/index.js",
       "start": "wp-scripts start src/frontend.js src/blocks/gift-message/index.js"
     },
     "devDependencies": {
       "@wordpress/scripts": "^30.0.0"
     }
   }
   ```

   ```json
   // src/blocks/gift-message/block.json
   {
     "$schema": "https://schemas.wp.org/trunk/block.json",
     "apiVersion": 3,
     "name": "my-checkout-fields/gift-message",
     "title": "Gift Message",
     "category": "woocommerce",
     "parent": ["woocommerce/checkout-shipping-methods-block"],
     "textdomain": "my-checkout-fields",
     "editorScript": "file:../../build/blocks/gift-message/index.js",
     "script": "file:../../build/blocks/gift-message/index.js",
     "style": "file:../../build/blocks/gift-message/style-index.css"
   }
   ```

## 示例

### 结账字段验证

应通过 Store API 更新回调在**服务器端**验证自定义结账数据。客户端过滤器(`__experimentalRegisterCheckoutFilters`)只能修改显示值(例如价格格式),不能验证表单字段。

```php
<?php
// Server-side validation in the Store API update callback
woocommerce_store_api_register_update_callback([
    'namespace' => 'my-checkout-fields',
    'callback'  => function (array $data) {
        if (isset($data['gift_message'])) {
            $message = sanitize_textarea_field($data['gift_message']);

            // Reject messages that contain URLs
            if (preg_match('#https?://#i', $message)) {
                throw new \Automattic\WooCommerce\StoreApi\Exceptions\RouteException(
                    'invalid_gift_message',
                    __('Gift messages cannot contain links.', 'my-checkout-fields'),
                    400
                );
            }

            WC()->session->set('gift_message', $message);
        }
    },
]);
```

在客户端处理来自 `extensionCartUpdate` 的错误响应,以显示验证消息:

```javascript
import { extensionCartUpdate } from "@woocommerce/blocks-checkout";

const handleChange = async (e) => {
  const value = e.target.value;
  setGiftMessage(value);
  try {
    await extensionCartUpdate({
      namespace: "my-checkout-fields",
      data: { gift_message: value },
    });
    setError(null);
  } catch (err) {
    setError(err.message);
  }
};
```

### 在特定购物车条件下禁用支付方式

```php
<?php
// Hide "Pay Later" payment method if cart contains digital-only products
add_filter(
    'woocommerce_blocks_payment_method_type_registration',
    function ($payment_method_registry) {
        $payment_method_registry->register(
            new class implements \Automattic\WooCommerce\Blocks\Payments\PaymentMethodTypeInterface {
                public function is_active() { return true; }
                public function get_payment_method_script_handles() { return []; }
                public function get_payment_method_data() { return []; }
                public function get_name() { return 'custom-payment-guard'; }
                public function initialize() {}
            }
        );
        return $payment_method_registry;
    }
);

add_filter('__experimental_woocommerce_blocks_payment_gateway_features_list', function ($features, $name) {
    if ($name === 'pay-later') {
        // Check if all items in cart are virtual/downloadable
        $cart_has_physical = false;
        foreach (WC()->cart->get_cart() as $item) {
            $product = $item['data'];
            if (!$product->is_virtual() && !$product->is_downloadable()) {
                $cart_has_physical = true;
                break;
            }
        }
        if (!$cart_has_physical) {
            $features['available'] = false;
        }
    }
    return $features;
}, 10, 2);
```

## 最佳实践

- **对必须在页面重新加载后保留的数据,使用 `extensionCartUpdate`,而不是本地状态** — 它通过 Store API 将数据存储在 WooCommerce 会话中
- **在服务器端清理所有自定义数据** — 对于写入订单元数据的任何数据,PHP 的 `sanitize_textarea_field`、`sanitize_text_field` 和 `absint` 都必不可少
- **使用 `@wordpress/scripts` 构建** — 它会自动处理 WordPress/Gutenberg 项目的依赖提取、webpack 配置和资源版本管理
- **内部区块使用 `block.json`** — 区块注册表需要 `block.json` 清单;它还支持在编辑器中自动加载资源
- **同时测试经典结账和区块结账** — 部分商店可能仍使用短代码结账;仅在检测到区块结账时才有条件地将脚本加入加载队列
- **使用 `woocommerce_store_api_register_update_callback` 进行服务器端验证** — 客户端验证可以被绕过;始终在回调中重新验证扩展数据
- **为所有元数据键和命名空间添加前缀**,使用你的插件 slug 避免与其他插件冲突

## 常见问题

| 问题 | 解决方法 |
|---------|----------|
| 内部区块未出现在编辑器中 | 确保 `block.json` 中的 `parent` 与目标结账步骤的区块名称完全一致;使用浏览器开发者工具确认父区块名称 |
| 扩展数据未持久保存到订单 | 添加 `woocommerce_checkout_order_created` 钩子,将会话数据传输到订单元数据 — Store API 会话数据不会自动复制到订单中 |
| SlotFill 组件未渲染 | `registerPlugin` 中必须包含 `scope: "woocommerce-checkout"`;省略它或使用错误的作用域会导致渲染被静默阻止 |
| 使用 `@wordpress/scripts` 时出现构建错误 | 必须在 `package.json` 脚本或 `wp-scripts.config.js` 中指定入口点;默认只构建 `src/index.js` |
| WooCommerce 降级后区块失效 | 将 `@woocommerce/blocks-checkout` 包版本固定为与 `composer.json` 中安装的 WooCommerce 版本相匹配 |
| `useSelect(CART_STORE_KEY)` 返回 undefined | 确保 `@woocommerce/block-data` 包位于 `wp_register_script` 的 `dependencies` 数组中 — 该 store 不能全局访问 |

## 相关 Skills

- @woocommerce-plugin-development
- @woocommerce-rest-api
- @gutenberg-block-development
- @checkout-flow-optimization
- @woocommerce-subscriptions

同类提示词

商业与职场

招聘面试轮次与面试官排期

提供岗位要求和面试官的可用时间,规划各轮评估内容、人员搭配及面试顺序,并起草题库和候选人通知。

# 面试安排 > 设计高效的面试流程,优化面试小组构成和日程安排,带来良好的候选人体验。 ## 何时使用此技能 - 设置多轮面试流程 - 协调面试小组日程 - 设计面试阶段 - 优化候选人体验 - 创建面试执行手册 ## 方法论基础 基于**结构化面试最佳实践**和**候选人体验研究**,结合: - 与阶段相适应的评估 - 面试小组多样性要求 - 招聘周期优化 - 候选人沟通 ## Claude的工作与由你决定的事项 | Claude的工作 | 由你决定 | |-------------|------------| | 设计面试阶段 | 最
可填 1 项
商业与职场

十五镜头产品营销视频分镜

填写营销文案与产品外观描述,按开场钩子、故事和促销安排分镜,逐条标明产品镜头或场景镜头。

你是一位精通营销心理学的商业视频分镜师。请根据营销文本和产品外观描述,创建具有强营销力的15个分镜。 营销文本:{text} 产品外观描述:{image} 【核心标记规则】⚠️ 极其重要 每个分镜必须在开头使用以下标记之一: - [产品镜头] - 画面中包含产品实体,需要保持产品外观一致性 - [场景镜头] - 不包含产品的纯环境、人物或情境画面 标记决定后端使用哪个生成模型,必须准确标注! 【营销策略分析】(内部分析,不输出) 分析营销文本,提取以下信息用于指导分镜创作: 1. 目标受众:识别目标人群特征,确定画面风格和场景选择 2. 核心卖点
可填 2 项中文原创
商业与职场

等距分层与爆炸图动画

为产品演示或信息图制作 2.5D 场景,用统一投影和分面明暗表现立体感,支持层叠展开及爆炸图动画。

# 等轴测(2.5D)动画 等轴测场景无需使用真正的透视,就能让讲解动画、UI 操作演示和信息图呈现出搭建而成的立体感:各轴等比例缩短、Z 轴方向堆叠的层级、拉伸立体块、爆炸图。整体风格几何感强、构图讲究——深度来自一致的轴向和各面的明暗处理,动效则通过逐层展示结构来实现。 ## 适用场景 - 用于讲解动画、产品 UI 或“工作原理”信息图的 2.5D 场景。 - 从下往上搭建的堆叠层级 / 楼层 / 技术栈塔。 - 拉伸立体块、等轴测网格、等轴测城市 / 服务器机架场景。 - 沿 Z 轴拆开再重新组装的爆炸图。 - 需要增添轻微生动感的静态等轴测
商业与职场

六页电影感演示文稿设计总览

选择浅色或深色方向,用图像模型把六页幻灯片合成一张电影感概览图,适合演示提案和版式评审。

# 演示文稿设计 创建一张**高端 6 页演示文稿设计展板**,将所有幻灯片合成为一张图片——让用户一眼看完整套演示文稿,适合电视屏幕展示,具有电影感。 主要用途:PPT 设计概念、主题演讲风格的幻灯片设计稿、战略演示文稿视觉方案、活动 / 新闻 / 体育 / 商业分析演示文稿、编辑式数据故事、高管演示文稿。 ## 图像生成要求 最终展板必须由**图像生成模型**生成(默认使用内置的 `image_gen` 工具,或经批准的项目图像生成工作流)。不要使用代码、SVG、HTML/CSS、canvas、图表、占位图或确定性形状脚本创建展板。这些方法只
商业与职场

十五款AI视频模型选型顾问

回答三至四个需求问题,按中文表现、音频、编辑能力、时长和可用性等条件获取模型推荐及理由。

# model-selector 15 个主流 AI 视频模型(11 商业 + 4 开源)的"购物顾问"。问用户 3-4 个关键问题,给出推荐 + 理由。 ## 何时不用此 skill - 用户已经确定要用某个模型 → 用对应的 `<model>-prompter` skill - 用户问"提示词怎么写" → 用 `seedance-prompter` / `kling-prompter` / `happyhorse-prompter` - 用户的提示词不工作 → 用 `seedance-debugger` ## 11 模型能力速查矩阵 | 模
中文原创
商业与职场

界面创意转视觉设计规格

填写界面用途、受众、尺寸和文案,将初步构想细化为包含网格、字体、配色与图像风格的设计规格。

# 设计优先的 UI 提示词技能 此技能适用于**设计优先的提示词编写**:将模糊的想法转化为严谨的规格说明,生成风格一致的 UI。 ## 核心原则 **像设计系统一样编写提示词,而不是许愿。** ## 提示词结构(复制/粘贴) 使用以下框架,然后填入空白。 ```text GOAL - What are we making? (e.g., landing page hero / onboarding / dashboard / carousel slide) - Who is it for? (persona) - What’s the suc
✓