我使用标准动作注册一个分类法:
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' );
}
后来,我希望根据一些参数获取产品。我还希望品牌层级(brand_heirarchy)包含在结果中。
$products = array(
'post_status' => 'publish',
'limit' => -1,
'category' => $parent_brand_slugs
);
$products = wc_get_products($product_args);
在返回的数据中,它会给我类别ID,例如:
[category_ids] => Array
(
[0] => 30
[1] => 27
[2] => 25
[3] => 24
)
但我希望它还能返回与产品相关联的品牌层级的ID。
我看到的大多数内容都是关于如何通过自定义分类法筛选产品,我只想知道哪些分类法与产品相关联。
我发现Woocommerce不允许这样做:https://github.com/woocommerce/woocommerce/issues/13138
我尝试使用过滤器woocommerce_product_object_query_args,但是无法弄清楚如何使用。还有一个产品搜索过滤器,但似乎不适用。
目前,我觉得最好的办法是循环遍历每个产品,并使用类似wp_get_object_terms($data['id'], 'brand_heirarchy')的方法,但这似乎效率不高。
我很久没有使用WordPress了,所以我真的想知道是否有更高效的方法可以获取与每个产品相关联的分类法。
谢谢。
哦,wp_get_object_terms和wp_get_post_terms似乎返回空数组,而产品确实被分配了品牌层级。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
使用wc_get_products()完全可以处理自定义分类法。你没有在正确的地方搜索,因为这是在WC_Product_Data_Store_CPT类中使用可用的过滤器钩子woocommerce_product_data_store_cpt_get_products_query来处理的。
因此,对于你的自定义产品分类法brand_heirarchy,你将使用以下代码:
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_custom_query_var', 10, 2 ); function handle_custom_query_var( $query_args, $query_vars ) { if ( ! empty( $query_vars['brand'] ) ) { $query_args['tax_query'][] = array( 'taxonomy' => 'brand_heirarchy', 'field' => 'slug', 'terms' => $query_vars['brand'], ); } return $query_args; }然后现在你可以在wc_get_products()函数中使用你的自定义分类法,例如:
$products = wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'brand' => $brand_slugs // array ) );现在应该可以了