Home  >  Article  >  Backend Development  >  How to Create a WooCommerce Product Variation with New Attribute Values Programmatically?

How to Create a WooCommerce Product Variation with New Attribute Values Programmatically?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-10 11:36:02415browse

How to Create a WooCommerce Product Variation with New Attribute Values Programmatically?

How to Create a WooCommerce Product Variation with New Attribute Values Programmatically

Introduction

WooCommerce allows you to create variable products with different attributes and values. To add new variations programmatically, you need to consider the following:

  • Ensure that the variable product (parent) has the desired attributes set.
  • For each variation, either create the new attribute value or set it if it already exists.

Custom Function to Create Product Variation

The following custom function will create a product variation for a given variable product ID:

function create_product_variation( $product_id, $variation_data ){
    // Get Variable product object (parent)
    $product = wc_get_product($product_id);

    // Create variation post data
    $variation_post = array(
        'post_title'    => $product->get_name(),
        'post_name'     => 'product-'.$product_id.'-variation',
        'post_status'   => 'publish',
        'post_parent'   => $product_id,
        'post_type'     => 'product_variation',
        'guid'          => $product->get_permalink()
    );

    // Insert variation post and create WC_Product_Variation object
    $variation_id = wp_insert_post( $variation_post );
    $variation = new WC_Product_Variation( $variation_id );

    // Iterate through variation attributes
    foreach ($variation_data['attributes'] as $attribute => $term_name )
    {
        $taxonomy = 'pa_'.$attribute; // Attribute taxonomy

        // Create taxonomy if doesn't exist
        if( ! taxonomy_exists( $taxonomy ) )
            register_taxonomy(
                $taxonomy,
                'product_variation',
                array(
                    'hierarchical' => false,
                    'label'        => ucfirst( $attribute ),
                    'query_var'    => true,
                    'rewrite'      => array( 'slug' => sanitize_title($attribute) ),
                ),
            );

        // Check if term exists and create if not
        if( ! term_exists( $term_name, $taxonomy ) )
            wp_insert_term( $term_name, $taxonomy ); // Create term

        $term_slug = get_term_by('name', $term_name, $taxonomy )->slug; // Get term slug

        // Check if post term exists and set if not
        $post_term_names =  wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
        if( ! in_array( $term_name, $post_term_names ) )
            wp_set_post_terms( $product_id, $term_name, $taxonomy, true );

        // Set attribute data in variation
        update_post_meta( $variation_id, 'attribute_'.$taxonomy, $term_slug );
    }

    // Set other variation data
    if( ! empty( $variation_data['sku'] ) )
        $variation->set_sku( $variation_data['sku'] );

    if( empty( $variation_data['sale_price'] ) ){
        $variation->set_price( $variation_data['regular_price'] );
    } else {
        $variation->set_price( $variation_data['sale_price'] );
        $variation->set_sale_price( $variation_data['sale_price'] );
    }
    $variation->set_regular_price( $variation_data['regular_price'] );

    if( ! empty($variation_data['stock_qty']) ){
        $variation->set_stock_quantity( $variation_data['stock_qty'] );
        $variation->set_manage_stock(true);
        $variation->set_stock_status('');
    } else {
        $variation->set_manage_stock(false);
    }
    
    $variation->set_weight(''); // Reset weight

    $variation->save();
}

Example Usage

For a variable product with attributes "Size" and "Color", you can create a variation as follows:

$parent_id = 746; // Variable product ID

$variation_data = array(
    'attributes' => array(
        'size'  => 'M',
        'color' => 'Green',
    ),
    'sku'           => '',
    'regular_price' => '22.00',
    'sale_price'    => '',
    'stock_qty'     => 10,
);

create_product_variation( $parent_id, $variation_data );

This will add a variation with the specified attributes and data to the variable product.

The above is the detailed content of How to Create a WooCommerce Product Variation with New Attribute Values Programmatically?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn