I register a taxonomy using standard actions:
add_action( 'init', 'product_brand_order_taxonomy' ); function product_brand_order_taxonomy() { $labels = array( 'name' => 'Brand Heirarchy', 'singular_name' => 'Brand Heirarchy', 'menu_name' => 'Brand Heirarchy', 'all_items' => 'All Brand Heirarchies', 'parent_item' => 'Parent Brand Heirarchy', 'parent_item_colon' => 'Parent Brand Heirarchy:', 'new_item_name' => 'New Brand Heirarchy Name', 'add_new_item' => 'Add New Brand Heirarchy', 'edit_item' => 'Edit Brand Heirarchy', 'update_item' => 'Update Brand Heirarchy', 'separate_items_with_commas' => 'Separate Brand Heirarchy with commas', 'search_items' => 'Search Brand Heirarchies', 'add_or_remove_items' => 'Add or remove Brand Heirarchies', 'choose_from_most_used' => 'Choose from the most used Brand Heirarchies', ); $args = array( 'labels' => $labels, 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_admin_column' => true, 'show_in_nav_menus' => true, 'show_tagcloud' => true, ); register_taxonomy( 'brand_heirarchy', 'product', $args ); register_taxonomy_for_object_type( 'brand_heirarchy', 'product' ); }
Later, I want to get the product based on some parameters. I also want the brand hierarchy (brand_heirarchy) to be included in the results.
$products = array( 'post_status' => 'publish', 'limit' => -1, 'category' => $parent_brand_slugs ); $products = wc_get_products($product_args);
In the returned data, it will give me the category ID, for example:
[category_ids] => Array ( [0] => 30 [1] => 27 [2] => 25 [3] => 24 )
But I want it to also return the brand-level ID associated with the product.
Most of the content I see is about how to filter products by custom taxonomies, I just want to know which taxonomies are associated with products.
I found out that Woocommerce doesn't allow this: https://github.com/woocommerce/woocommerce/issues/13138
I tried using the filter woocommerce_product_object_query_args, but couldn't figure out how to use it. There is also a product search filter, but it doesn't seem to apply.
Currently, I think the best way is to loop through each product and use something like wp_get_object_terms($data['id'], 'brand_heirarchy'), but this doesn't seem efficient.
I haven't used WordPress in a long time, so I'd really like to know if there's a more efficient way to get the taxonomies associated with each product.
Thanks.
Oh, wp_get_object_terms and wp_get_post_terms seem to return empty arrays, while products are indeed assigned brand tiers.
Using wc_get_products() can completely handle custom taxonomies. You are not searching in the right place as this is handled in the WC_Product_Data_Store_CPT class using the available filter hook woocommerce_product_data_store_cpt_get_products_query.
So, for your custom product taxonomy brand_heirarchy, you would use the following code:
Then now you can use your custom taxonomy in the wc_get_products() function, for example:
It should be OK now