2017-10-15 116 views
1

我目前使用wp_insert_post()函數成功地將產品添加到Woocommerce中。根據Woocommerce中的產品標籤自動分配產品類別

我現在試圖根據產品標籤將產品分配給相關類別。例如,如果產品添加了產品標籤「戒指」或「項鍊」,則會自動分配到「珠寶」類別。

使用以下函數,我可以在帖子上實現正確的功能,但在嘗試使用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!

回答

0

試試這個代碼:

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'); 
+0

謝謝!當通過管理員後端添加產品時,這非常合適,但是,在我以前以編程方式添加產品時似乎並沒有觸發。我猜這是因爲對象條款(產品標籤)在帖子保存後被添加?我試過使用行爲'set_object_terms'而不是'save_post',這似乎工作,但只添加了與第一個標籤相關的類別。有任何想法嗎? –

+0

等一下,你說你正在編程。在這種情況下,根本沒有必要使用濾波器。只需在wp_insert_post()用法之後的某處添加代碼即可。 –

+0

當然 - 現在你已經說得很完美了。不知道爲什麼我一開始就沒有考慮過這樣做!噢 - 非常感謝您的幫助! –

相關問題