WordPress自定义Gutenberg块:如何获取产品更多信息(例如价格)
获取WooCommerce产品额外信息(如价格)的方法
默认情况下,使用getEntityRecords获取产品时,不会自动返回WooCommerce专属的价格等字段,需要在查询参数中显式指定要获取的字段,或者配置元字段查询。
修改后的代码示例
1. 获取基础价格字段
如果只需要产品的常规价格、促销价格等核心价格信息,可以在查询参数中通过_fields指定需要的字段:
const { posts } = useSelect( (select) => { const posts = select('core').getEntityRecords('postType', 'product', { per_page: numberOfItems, _embed: true, // 明确指定需要的字段,包含WooCommerce价格相关字段 _fields: ['id', 'title', 'price', 'regular_price', 'sale_price', 'permalink'] }); return { posts }; }, [numberOfItems], );
获取到产品数据后,就可以直接通过以下方式访问价格:
// 遍历产品并输出价格信息 posts?.forEach(product => { console.log('产品售价:', product.price); console.log('常规价格:', product.regular_price); console.log('促销价格:', product.sale_price); });
2. 获取自定义元字段
如果需要获取库存、SKU等其他产品元信息,可以添加meta参数指定要查询的元字段:
const { posts } = useSelect( (select) => { const posts = select('core').getEntityRecords('postType', 'product', { per_page: numberOfItems, _embed: true, _fields: ['id', 'title', 'price', 'meta'], // 指定要获取的自定义元字段 meta: { key: '_stock' // 库存数量对应的元字段键名 } }); return { posts }; }, [numberOfItems], );
3. 处理变量产品
如果你的产品包含变体,需要获取变体价格的话,可以在_fields中加入variations字段,关联获取变体数据:
const { posts } = useSelect( (select) => { const posts = select('core').getEntityRecords('postType', 'product', { per_page: numberOfItems, _embed: true, _fields: ['id', 'title', 'price', 'variations'] }); return { posts }; }, [numberOfItems], );
注意事项
- 确保你的WooCommerce版本支持REST API中的价格字段,大部分新版本都已默认支持。
- 如果某些字段无法获取,可能需要通过WooCommerce的钩子(如
woocommerce_rest_prepare_product)手动注册需要的字段到REST响应中。
内容的提问来源于stack exchange,提问作者Jarosław Puślecki
相关产品推荐
相关产品推荐

