0

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?

aynber
  • 22,380
  • 8
  • 50
  • 63
Mario
  • 353
  • 1
  • 5
  • 17
  • 2
    This question needs some refinement. Where is a code sample showing your current process? Where is the evidence that you've done a [google search](https://stackoverflow.com/questions/26690047/how-to-programatically-set-the-category-for-a-new-woocommerce-product-creation) on this question? This is not a free programming service; it's to help people who are stuck and have already tried various solutions without success. – Kaboodleschmitt Aug 21 '20 at 15:05
  • I tried to search for this issue, but couldn't find anything. Your link is a first start, but I don't know how to search the product title for the category name to automatically add it to the category. I added some more information to my post though. – Mario Aug 21 '20 at 15:51

1 Answers1

2
  1. Load all product categories via get_product_categories( $fields );

  2. Use get the product name to find the name of the product

  3. 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);
Kaboodleschmitt
  • 453
  • 3
  • 13