在WooCommerce中将产品自动分配给定义的产品类别 [英] Automatically assign products to a defined product category in WooCommerce
问题描述
在Woocommerce中,如果产品具有特定的自定义字段值(使用高级自定义字段插件生成此字段),我会尝试自动将给定产品类别分配给产品。
In Woocommerce, I am trying to automatically assign a given product category to products if they have a specific custom field value (Using Advanced custom fields plugin to generate this field).
在我的 functions.php
中,我有:
function auto_add_category ($product_id = 0) {
if (!$product_id) return;
$post_type = get_post_type($post_id);
if ( "product" != $post_type ) return;
$field = get_field("city");
if($field == "Cassis"){
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
$product_cat_id = $term->term_id;
if($product_cat_id != 93){
wp_set_post_terms( $product_id, 93, 'product_cat', true );
}
break;
}
}
}
add_action('save_post','auto_add_category');
但这不起作用。
推荐答案
对于 save_post
钩子,有3个参数:
For save_post
hook there is 3 arguments:
-
$ post_id
(帖子ID), -
$ post
(WP_Post
对象), -
$ update
(无论这是现有的帖子是否正在更新:true
或false
)。
$post_id
(the post ID),$post
(theWP_Post
object),$update
(whether this is an existing post being updated or not:true
orfalse
).
ACF get_field()
函数可以无需在此处指定帖子ID 。
The ACF get_field()
function works without any need of specifying the post ID in here.
另外,要使代码更紧凑,轻巧和高效,应使用条件函数 > has_term()
与 term_exists()
而不是 get_the_terms()
(+一个foreach循环)正在获取您网站上的所有现有产品类别…
Also, to make your code more compact, light and efficient, you should use conditional functions has_term()
with term_exists()
instead of get_the_terms()
(+ a foreach loop) that is getting all the existing product categories on your website…
所以您应该这样尝试:
// Only on WooCommerce Product edit pages (Admin)
add_action( 'save_post', 'auto_add_product_category', 50, 3 );
function auto_add_product_category( $post_id, $post, $update ) {
if ( $post->post_type != 'product') return; // Only products
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( ! current_user_can( 'edit_product', $post_id ) )
return $post_id;
if ( ! ( $post_id && function_exists( 'get_field' ) ) )
return; // Exit if ACF is not enabled (just to be sure)
if ( 'Cassis' != get_field( 'city' ) )
return; // Exit if ACF field "city" has 'Cassis' as value
$term_id = 93; // <== Your targeted product category term ID
$taxonomy = 'product_cat'; // The taxonomy for Product category
// If the product has not "93" category id and if "93" category exist
if ( ! has_term( $term_id, 'product_cat', $post_id ) && term_exists( $term_id, $taxonomy ) )
wp_set_post_terms( $post_id, $term_id, $taxonomy, true ); // we set this product category
}
代码位于<$ c活动子主题(或活动主题)的$ c> function.php 文件。
经过测试并可以工作。它也应该对您有用。
Tested and works. It should works for you too.
这篇关于在WooCommerce中将产品自动分配给定义的产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!