在使用 WP All Imports 插件导入产品时,我正在尝试从产品标签自动设置 Woocommerce 产品类别。
例如:我正在将特定的面包屑 slug 作为产品标签导入:运动/鞋子/跑鞋 > 现在我想将该 slug 连接到预定义的类别层次结构:
标签: 运动/鞋/跑鞋 => 产品猫: 鞋/跑步
也许有一个插件可以在预定义的产品类别中放置标签以显示类别中的选定产品?
我发现以下代码接近实现目标所需的代码:
function auto_add_category ($product_id = 0) {
if (!$product_id) return;
// because we use save_post action, let's check post type here
$post_type = get_post_type($post_id);
if ( "product" != $post_type ) return;
$tag_categories = array (
'ring' => 'Jewellery'
'necklace' => 'Jewellery',
'dress' => 'Clothing',
);
// get_terms returns ALL terms, so we have to add object_ids param to get terms to a specific product
$product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'object_ids' => $product_id ) );
foreach ($product_tags as $term) {
if ($tag_categories[$term->slug] ) {
$cat = get_term_by( 'name', $tag_categories[$term->slug], 'product_cat' );
$cat_id = $cat->term_id;
if ($cat_id) {
$result = wp_set_post_terms( $product_id, $cat_id, 'product_cat', true );
}
}
}
}
add_action('save_post','auto_add_category');