I want to automatically add products to a category if their name contains the category (for example the product name is: Awesome brand baseball bat, the product should automatically be added to the category baseball bat). Is there a plugin that can automatically do this or even better: is it possible to add a rule to WP All Import to do this?
Setting the category like
$product->set_category_ids([ 300, 400 ] );
shouldn't be the problem, but how can I compare the articles names with all my categories so I can automatically add the products to them?
Load all product categories via get_product_categories( $fields );
Find the name of the product
Loop through the categories and compare each of them to the product name. Depending on your situation and what values are in product category title or product names, you may need to use a regex for this
When done, your code should look something like this:
$product_category_list = $product->get_categories();
$product_name = $product->get_name();
$categories_to_put_product_in = array();
foreach($product_category_list as $current_category) {
if (strpos($product_name, $current_category->term_id) !== false) {
$categories_to_put_product_in[] = $current_category;
}
}
$product->set_category_ids($categories_to_put_product_in);