Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get woocommerce product category using Gutenberg getEntityRecords

Is it possible to get all product categories using Gutenberg getEntityRecords()?

I have found a code for getting post category as follows

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

Can I alter the above code to get all woocommerce products category?

like image 329
Team Techi Avatar asked Oct 24 '25 12:10

Team Techi


2 Answers

I have also searched the same thing. But at last I have decided to use the apiFetch for this tasks (following woocommerce-gutenberg-products-block plugin).

for example a sample use case :

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);
});
like image 95
shaad Ishtiaque Avatar answered Oct 26 '25 02:10

shaad Ishtiaque


You were actually very close to getting getEntityRecords to work. The only issue was product categories are a different taxonomy than post categories.

Here's a full example utilizing the useSelect hook:

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,
        ]),
    };
});
like image 43
jmotes Avatar answered Oct 26 '25 02:10

jmotes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!