【发布时间】:2018-03-26 22:43:38
【问题描述】:
我目前有一个函数可以使用 wp_insert_post() 成功地将产品添加到 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 中糊里糊涂,任何帮助都将不胜感激!
【问题讨论】:
标签: php wordpress function woocommerce