I want to automatically assign product category based on assigned product tag. I want to do exactly what this ( https://wordpress.org/plugins/auto-assign-post-category/ ) plugin does, but with products, not posts. I have also this code:
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 (
'Biblioteka' => 'Biblioteki',
'Biurko' => 'Biurka',
'Fotel' => 'Fotele',
'Komoda' => 'Komody',
'Konsola' => 'Konsole',
'Kredens' => 'Kredensy',
'Krzesło' => 'Krzesła',
'Lustro' => 'Lustra',
'Ława' => 'Ławy',
'Łóżko' => 'Łóżka',
'Regał na książki' => 'Regały na książki',
'Sofa' => 'Sofy',
'Stolik' => 'Stoliki',
'Stół' => 'Stoły',
'Stół ogrodowy' => 'Stoły ogrodowe',
'Szafka nocna' => 'Szafki nocne',
'Szafka RTV' => 'Szafki RTV',
'Szafa' => 'Szafy',
'Toaletka' => 'Toaletki',
'Witryna' => 'Witryny',
);
// 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('publish_post','auto_add_category');
But I can't make it work. Products are already on site. Thanks for help!