[英]Auto assign Woocommerce Product Categories from Product Tags on import
[英]Automatically assign products to categories based on their product tags in Woocommerce
我目前有一個使用wp_insert_post()成功將產品添加到Woocommerce的功能。
我現在正嘗試根據產品標簽將產品分配到相關類別。 例如,如果添加了帶有“ ring”或“ necklace”產品標簽的產品,則會自動將其分配給“珠寶”類別。
使用以下功能,我能夠在帖子上實現正確的功能,但是對於woocommerce中使用的產品帖子類型嘗試使此功能不起作用。
職位作品:
function auto_add_category ($post_id = 0) {
if (!$post_id) return;
$tag_categories = array (
'ring' => 'Jewellery',
'necklace' => 'Jewellery',
'dress' => 'Clothing',
);
$post_tags = get_the_tags($post_id);
foreach ($post_tags as $tag) {
if ($tag_categories[$tag->name] ) {
$cat_id = get_cat_ID($tag_categories[$tag->name]);
if ($cat_id) {
$result = wp_set_post_terms( $post_id, $tags = $cat_id, $taxonomy = 'category', $append = true );
}
}
}
}
add_action('publish_post','auto_add_category');
我試圖將代碼重新用於產品,如下所示:
function auto_add_category ($product_id = 0) {
if (!$product_id) return;
$tag_categories = array (
'ring' => 'Jewellery'
'necklace' => 'Jewellery',
'dress' => 'Clothing',
);
$product_tags = get_terms( array( 'taxonomy' => 'product_tag') );
foreach ($product_tags as $tag) {
if ($tag_categories[$tag->name] ) {
$cat = get_term_by( 'name', $tag_categories[$tag->name], 'product_cat' );
$cat_id = $cat->term_id;
if ($cat_id) {
$result = wp_set_post_terms( $product_id, $tags = $cat_id, $taxonomy = 'product_cat', $append = true );
}
}
}
}
add_action('publish_product','auto_add_category');
但是,它不會在創建產品時分配相關類別。 這位新手編碼員在wordpress上摸索自己的方式,將對您的幫助非常感激!
試試這個代碼:
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');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.