Gert Snijder
Gert Snijder

Reputation: 21

Auto assign Woocommerce Product Categories from Product Tags on import

I am trying to set automatically Woocommerce Product Categories from Product Tags when importing products using WP All Imports plugin.

For example: I am importing specific breadcrumb slugs as Product tags: Sports/Shoes/Running Shoes > Now I wanne connect that slug to an predefined Category hierarchy:

Tag: Sports/Shoes/Running Shoes => Product cat: Shoes/Running

Maybe there is an plugin where to drop Tags in predifined Product Categorys to show the selected products in category?

I found the following code that is close to what I need to achieve my goal:

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

Upvotes: 2

Views: 1164

Answers (1)

Artemiy Egorov
Artemiy Egorov

Reputation: 61

First of all you need to understand the logic by yourself. For me its not clear how can you filter which one of the tag collection should be organized like described.

Once you know the logic you can use the 'Function editor' field in the import settings. At the bottom of the screen where you have the mapping of all import.

You can put your function there and use it in the tag field. For example:

you have the function :

<?php
function import_rearrange_tags( $tag, $count = 1 ) {
  // Some code here
  return $tag;
}
?>

So you can use it your mapping like a filter like this :

[import_rearrange_tags({tags[1]}, 3)]

I use the second parameter to show the whole idea.

Upvotes: 1

Related Questions