Access our premium support and let us know your problems, we will help you solve them.

0
No products in the cart.

Forum Replies Created

Viewing 1 post (of 1 total)
  • Author
    Posts
  • blanksarakinos
    Participant

    You can also achieve this using the new native functions for setting/getting data from postmeta.

    Here is an example that works ( based on the default dummy products of Woocommerce 3)

    //Create main product
    $product = new WC_Product_Variable();
    
    //Create the attribute object
    $attribute = new WC_Product_Attribute();
    //pa_size tax id
    $attribute->set_id( 1 );
    //pa_size slug
    $attribute->set_name( 'pa_size' );
    
    //Set terms slugs
    $attribute->set_options( array(
            'blue',
            'grey'
    ) );
    $attribute->set_position( 0 );
    
    //If enabled
    $attribute->set_visible( 1 );
    
    //If we are going to use attribute in order to generate variations
    $attribute->set_variation( 1 );
    
    $product->set_attributes(array($attribute));
    
    //Save main product to get its id
    $id = $product->save();
    
    
    $variation = new WC_Product_Variation();
    $variation->set_regular_price(5);
    $variation->set_parent_id($id);
    
    //Set attributes requires a key/value containing
    // tax and term slug
    $variation->set_attributes(array(
            'pa_size' => 'blue'
    ));
    
    //Save variation, returns variation id
    $variation->save();
    

    You can add things like weight, tax, sku etc using the native functions available from Woocommerce 3 and on like set_price, set_sku ect.

    Wrap it within a function and you are good to go.

Viewing 1 post (of 1 total)