0

I'm trying to add product attributes in WooCommerce with a plugin that I'm creating. For example, when admin creates a new product with an attribute size, a second attribute called color needs to be created automatically and for every size there needs to be a color.

This is the code that I'm already running:

function add_product_variations( $meta_id, $post_id, $meta_key, $meta_value ) {
    global $wpdb;
    if ( get_post_type( $post_id ) == 'product' ) {
        $product = wc_get_product( $post_id );

        $availableColors = ['red', 'blue', 'green'];

        $product_attributes = array();
        $product_attributes['colors'] = array(
            'name' => 'Colors',
            'value' => implode('|', $availableColors),
            'position' => 0,
            'is_visible' => 1,
            'is_variation' => 1,
            'is_taxonomy' => 0
        );
        update_post_meta($product->id, '_product_attributes', $product_attributes);

        wp_add_object_terms($product->id, implode('|', $availableColors), 'colors', true);

        foreach ($availableColors as $color) {
            $colorClean = preg_replace("/[^0-9a-zA-Z_-] +/", "", $color);
            $post_name = 'product-' . $product->id . '-color-' . $colorClean;
            $my_post = array(
                'post_title' => 'color ' . $color . ' for #' . $product->id,
                'post_name' => $post_name,
                'post_status' => 'publish',
                'post_parent' => $product->id,
                'post_type' => 'product_variation',
                'guid' => home_url() . '/?product_variation=' . $post_name
            );
            $attID = $wpdb->get_var("SELECT count(post_title) FROM $wpdb->posts WHERE post_name like '$post_name'");
            if ($attID < 1) {
                $attID = wp_insert_post($my_post);
            }
            update_post_meta($attID, 'attribute_dates', $color);
            update_post_meta($attID, '_regular_price', 100);
            update_post_meta($attID, '_sku', $post_name);
            update_post_meta($attID, '_virtual', 'no');
            update_post_meta($attID, '_downloadable', 'no');
            update_post_meta($attID, '_manage_stock', 'no');
            update_post_meta($attID, '_stock_status', 'instock');
        }
    }
}
add_action( 'added_post_meta', 'add_product_variations', 10, 4 );

This code works fine when I don't create product attributes manually. It only creates one product attribute called color with options 'red', 'blue' and 'green'; but the problem comes when I add manually a product attribute. Then the code is not creating the color attribute anymore.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.