【问题标题】:Get woocommerce product category using Gutenberg getEntityRecords使用 Gutenberg getEntityRecords 获取 woocommerce 产品类别
【发布时间】:2019-07-20 21:12:21
【问题描述】:

是否可以使用 Gutenberg getEntityRecords() 获取所有产品类别?

我找到了获取帖子类别的代码如下

var query = {per_page: 100}
categoriesList =  getEntityRecords( 'taxonomy', 'category', query );

我可以更改以上代码以获取所有 woocommerce 产品类别吗?

【问题讨论】:

  • - 您是否在 componentDidMount 生命周期内使用 WordPress REST API 通过获取请求获取数据?您还可以查看 WooCommerce 默认块以了解这些块如何请求数据。

标签: javascript wordpress woocommerce custom-taxonomy gutenberg-blocks


【解决方案1】:

我也搜索过同样的东西。但最后我决定使用 apiFetch 来完成这项任务(在 woocommerce-gutenberg-products-block 插件之后)。

例如一个示例用例:

const apiFetch = wp.apiFetch;
const { addQueryArgs } = wp.url;

const productCategories = (queryArgs) => {
    return apiFetch({
        path: addQueryArgs(`wc/store/products/categories`, {
            per_page: 0,
            ...queryArgs,
        }),
    });
};

productCategories().then((categories) => {
        console.log(categories);
});

【讨论】:

    【解决方案2】:

    您实际上非常接近让getEntityRecords 工作。唯一的问题是产品类别与帖子类别的分类不同。

    这是一个使用 useSelect 钩子的完整示例:

    import { useSelect } from "@wordpress/data";
    
    const { productCategories, isSearching } = useSelect((select) => {
        const { getEntityRecords, isResolving } = select("core");
        const query = { per_page: 100 };
    
        return {
            productCategories: getEntityRecords("taxonomy", "product_cat", query),
            isSearching: isResolving("getEntityRecords", [
                "taxonomy",
                "product_cat",
                query,
            ]),
        };
    });
    

    【讨论】:

      猜你喜欢
      • 2016-01-09
      • 2014-06-27
      • 1970-01-01
      • 2018-02-07
      • 2014-01-27
      • 2021-08-05
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      相关资源
      最近更新 更多