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).
In my functions.php
I have :
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');
But this doesn't work. Any idea please?
For
save_post
hook there is 3 arguments:$post_id
(the post ID),$post
(theWP_Post
object),$update
(whether this is an existing post being updated or not:true
orfalse
).The ACF
get_field()
function works without any need of specifying the post ID in here.Also, to make your code more compact, light and efficient, you should use conditional functions
has_term()
withterm_exists()
instead ofget_the_terms()
(+ a foreach loop) that is getting all the existing product categories on your website…So you should try it this way instead:
Code goes in
function.php
file of the active child theme (or active theme).Tested and works. It should works for you too.
Seems like you're using ACF?
get_field()
requires the post id to be passed to it if not used in the loop, so you should make that line$field = get_field("city",$product_id);
.Also, replace
$post->ID
with$product_id
inget_the_terms()
Hope that helps