1

I'm trying to create a product in php with variations. I've gotten the product creation but I can't seem to figure out how to create variations for it. Googling only returns adding variations to existing products, but I'm trying to create a product completely from scratch, give it an attribute, and using that attribute to make variations from an array of strings.

$team = get_post();     
        $post_id = wp_insert_post( 
        array( 'post_title' => $team->post_title,
                'post_type' => 'product',
                'post_status' => 'publish'
            )
        );
        wp_set_object_terms( $post_id, 'simple', 'variable' );
        update_post_meta( $post_id, '_sku', 'FEES-'.$team->ID );

This is what I have so far.

Marnie Rodriguez
  • 431
  • 2
  • 8
  • 22
  • This might help you. https://stackoverflow.com/a/47766413/5772301 – Gautam Golakiya May 29 '21 at 05:22
  • Not really, it didn't generate a variation of the product – Marnie Rodriguez May 31 '21 at 16:32
  • @MarnieRodriguez, are you saying that you are unable to create a variation product from the code link of which is shared above? Because it creates a new variation product from scratch as you are trying to achieve. i can see that you have successfully created a variable product and the above code should be suffice to create variations and attach it to the parent which you created earlier. Can you explain why this isn't solving your problem ? – bhanu Jun 01 '21 at 17:38
  • @Bhanu, the link provided is not creating a variation of the product. The above code IS creating a product that is a "variation product", but I'm trying to make a variation of that product. And example would be the above code making a shirt product, and now I'm trying to make a "red" shirt and "blue" shirt. – Marnie Rodriguez Jun 02 '21 at 16:24
  • @MarnieRodriguez, the above code is actually making a `red shirt` and `blue shirt` using `shirt` see Usage (example with 2 attributes) in that answer. `$parent_id` is 746 (shirt) and attributes are defined at `$variation_data['attributes']`. – bhanu Jun 02 '21 at 16:29
  • @Bhanu I'm sorry but its not working for me. – Marnie Rodriguez Jun 02 '21 at 17:20
  • @MarnieRodriguez, update your question om how you tried the above code and I will try to look at it. – bhanu Jun 02 '21 at 17:21

1 Answers1

0

I think you need to use "WC_Product_Variation"class for registering variations and wp_insert_post for creating the product variable.

have a look at this example, it might help you or give an idea.

Create WooCommerce Variable Product with Attributes

See more info in woocommerce docs: WC_Product_Variation