How to create Simple and Variable Products from JSON data?
-
The product data I fetched from json
$json_result = json_decode($response, true);
OUTPUT: Array ( [0] => Array ( [slug] => Vialli VJ21R47 Kosmos Jean Ink [title] => Vialli VJ21R47 Kosmos Jean Ink [contentHTML] => Looking for a pair of jeans that are out-of-this-world? [brand] => Vialli [productCategory] => Jeans [type] => Variable [tags] => Array ( [0] => vialli [1] => new ) [active] => [variations] => Array ( [0] => Array ( [options] => Array ( [0] => Array ( [name] => Color [value] => Ink ) [1] => Array ( [name] => Size [value] => 31 ) ) [sku] => 1185029INKS31 [barcode] => [weight] => [variantInventoryTracker] => shopify [variantInventoryPolicy] => deny [variantFulfillmentService] => manual [imageSrcs] => Array ( [0] => https://cdn.shopify.com/s/files/1/1485/6954/products/51-856_1_600x.jpg?v=1671723048 ) [price] => 2850 [priceCompareAt] => 2850 [quantity] => 4 ) [1] => Array ( [options] => Array ( [0] => Array ( [name] => Color [value] => Ink ) [1] => Array ( [name] => Size [value] => 33 ) ) [sku] => 1185029INKS33 [barcode] => [weight] => [variantInventoryTracker] => shopify [variantInventoryPolicy] => deny [variantFulfillmentService] => manual [imageSrcs] => Array ( [0] => https://cdn.shopify.com/s/files/1/1485/6954/products/51-856_2_600x.jpg?v=1671723122 ) [price] => 2850 [priceCompareAt] => 2850 [quantity] => 3 ) [2] => Array ( [options] => Array ( [0] => Array ( [name] => Color [value] => Ink ) [1] => Array ( [name] => Size [value] => 46 ) ) [sku] => 1185029INKS46 [barcode] => [weight] => [variantInventoryTracker] => shopify [variantInventoryPolicy] => deny [variantFulfillmentService] => manual [imageSrcs] => Array ( [0] => https://cdn.shopify.com/s/files/1/1485/6954/products/51-856_2_600x.jpg?v=1671723122 ) [price] => 2850 [priceCompareAt] => 2850 [quantity] => 2 ) [3] => Array ( [options] => Array ( [0] => Array ( [name] => Color [value] => Blue ) [1] => Array ( [name] => Size [value] => 31 ) ) [sku] => 1185029BLUES31 [barcode] => [weight] => [variantInventoryTracker] => shopify [variantInventoryPolicy] => deny [variantFulfillmentService] => manual [imageSrcs] => Array ( [0] => https://cdn.shopify.com/s/files/1/1485/6954/products/51-856_2_600x.jpg?v=1671723122 ) [price] => 2850 [priceCompareAt] => 2850 [quantity] => 1 ) ) [availableOptions] => Array ( [0] => Array ( [optionName] => Color [optionValues] => Array ( [0] => Ink [1] => Blue ) ) [1] => Array ( [optionName] => Size [optionValues] => Array ( [0] => 31 [1] => 33 [2] => 46 ) ) ) [status] => [weightUnit] => kg [sku] => [barcode] => [price] => [priceCompareAt] => [imageSrcs] => [created] => ) [1] => Array ( [slug] => Vialli VJ22R44 Buscott Jeans blue [title] => Vialli VJ22R44 Buscott Jeans blue [contentHTML] => Looking for something unique in your denim wardrobe? [brand] => Vialli [productCategory] => Jeans [type] => Variable [tags] => Array ( [0] => vialli [1] => new ) [active] => [variations] => Array ( [0] => Array ( [options] => Array ( [0] => Array ( [name] => Color [value] => Blue ) [1] => Array ( [name] => Size [value] => 29 ) ) [sku] => 1185027BLUS29 [barcode] => [weight] => [variantInventoryTracker] => shopify [variantInventoryPolicy] => deny [variantFulfillmentService] => manual [imageSrcs] => Array ( [0] => https://cdn.shopify.com/s/files/1/1485/6954/products/51-856_2_600x.jpg?v=1671723122 ) [price] => 2850 [priceCompareAt] => 2850 [quantity] => 2 ) ) [availableOptions] => Array ( [0] => Array ( [optionName] => Color [optionValues] => Array ( [0] => Blue ) ) [1] => Array ( [optionName] => Size [optionValues] => Array ( [0] => 29 ) ) ) [status] => [weightUnit] => kg [sku] => [barcode] => [price] => [priceCompareAt] => [imageSrcs] => [created] => ) [2] => Array ( [slug] => Simple Product No Variations [title] => Simple Product No Variations [contentHTML] => This is a test product with no variations [brand] => Vialli [productCategory] => T-Shirts [type] => Simple [tags] => Array ( [0] => vialli [1] => new [2] => Mens [3] => Tops [4] => Mens T-Shirts [5] => Ink ) [active] => [variations] => [availableOptions] => [status] => [weightUnit] => g [sku] => TESTSKU [barcode] => TESTBARCODE [price] => 500 [priceCompareAt] => 500 [imageSrcs] => Array ( [0] => https://cdn.shopify.com/s/files/1/1485/6954/products/51-856_2_600x.jpg?v=1671723122 ) [created] => )
NOw from above data I want to create product in woocommerce. So I did like this
foreach ((array)$json_result as $product) { $variations = $product['variations']; $price = $product['price']; $salePrice = $product['priceCompareAt']; $availableOptions = $product['availableOptions']; $regular_price = number_format((float) $price, 2, '.', ''); $selling_price = number_format((float) $salePrice, 2, '.', ''); //product tags create $tags = isset($product['tags']) ? $product['tags'] : ''; foreach ($tags as $tag) { $tagname = $tag; $tagg = term_exists($tagname); if ($tagg != '' && $tagg > 0) { $tag_id = $tagg; } else { try { $tag_data = [ 'name' => $tagname, ]; $tags_ids = $woocommerce->post('products/tags', $tag_data); $tag_id = $tags_ids->id; } catch (Exception $e) { //echo 'Exception here'; } } } //end create tags. if ($product['type'] === 'Simple') { $product_datas = [ 'name' => isset($product['title']) ? $product['title'] : '', 'description' => isset($product['contentHTML']) ? $product['contentHTML'] : '', 'categories' => [ [ 'id' => $catID ], ], 'regular_price' => $regular_price, 'sale_price' => $selling_price, 'sku' => isset($product['sku']) ? $product['sku'] : '', 'type' => 'simple', 'status' => 'publish' ]; $simple_data = $woocommerce->post('products', $product_datas); } // Fetch variant data $optionNames = []; $optionValues = []; // Loop through the available options array. if (is_countable($availableOptions) && count($availableOptions) > 0) { for ($a = 0; $a < count($availableOptions); $a++) { $optionNames[] = $availableOptions[$a]['optionName']; $optionValues[$availableOptions[$a]['optionName']][] = $availableOptions[$a]['optionValues']; } } $attribute_ids = []; if (is_countable($optionNames) && count($optionNames) > 0) { for ($i = 0; $i < count($optionNames); $i++) { // Get the next option name. $attributeName = $optionNames[$i]; $attribute_id = $wpdb->get_var("select attribute_id from {$wpdb->prefix}woocommerce_attribute_taxonomies where attribute_name='" . $attributeName . "'"); if ($attribute_id != '' && $attribute_id > 0) { $atID = $attribute_id; } else { try { $att_data = [ 'name' => isset($attributeName) ? $attributeName : '', 'variation' => true, 'visible' => true, ]; // Create the attribute without options for now $att_name = $woocommerce->post('products/attributes', $att_data); $atID = $att_name->id; } catch (Exception $e) { // Handle the exception } } $attribute_ids[] = $atID; } } if (!function_exists('save_product_attribute_terms')) { // Function to save attribute terms function save_product_attribute_terms($woocommerce, $optionValues) { foreach ($optionValues as $optionName => $values) { try { // Check if the attribute already exists $existing_attributes = $woocommerce->get('products/attributes', ['name' => $optionName]); if (!empty($existing_attributes)) { // Loop through existing attributes to find the correct one foreach ($existing_attributes as $existing_attribute) { if ($existing_attribute->name === $optionName) { $attribute_id = $existing_attribute->id; break; // Stop the loop when the correct attribute is found } } } // If the attribute doesn't exist, create it if (empty($attribute_id)) { $attribute_data = [ 'name' => $optionName, ]; $attribute = $woocommerce->post('products/attributes', $attribute_data); if (!empty($attribute->id)) { $attribute_id = $attribute->id; } else { // Handle attribute creation failure continue; // Skip to the next attribute if creation fails } } // Now associate the values with the attribute foreach ($values as $value) { if (is_array($value)) { // If $value is an array, loop through its elements for ($td = 0; $td < count($value); $td++) { // Check if the term already exists for this attribute $term_exists = $woocommerce->get('products/attributes/' . $attribute_id . '/terms', ['name' => $value[$td]]); // Create the term if it doesn't exist if (empty($term_exists)) { $term_data = [ 'name' => $value[$td], ]; $woocommerce->post('products/attributes/' . $attribute_id . '/terms', $term_data); } } } else { // Check if the term already exists for this attribute $term_exists = $woocommerce->get('products/attributes/' . $attribute_id . '/terms', ['name' => $value]); // Create the term if it doesn't exist if (empty($term_exists)) { $term_data = [ 'name' => $value, ]; $woocommerce->post('products/attributes/' . $attribute_id . '/terms', $term_data); } } } } catch (HttpClientException $e) { // Handle the exception } } } } // Call the function to save attribute terms save_product_attribute_terms($woocommerce, $optionValues); $productTitle = isset($product['title']) ? $product['title'] : ''; $foundPost = post_exists($productTitle); if ($foundPost <= 0) { $allAttributes = $woocommerce->get('products/attributes'); $createAttribute = []; foreach ($allAttributes as $allAttribute) { $id = $allAttribute->id; $name = $allAttribute->name; $allTerms = $woocommerce->get('products/attributes/' . $id . '/terms'); $optVal = []; foreach ($allTerms as $allTerm) { $optVal[] = $allTerm->name; $createAttributes = array( 'id' => $id, 'variation' => True, 'visible' => True, 'name' => $name, 'options' => $optVal ); $createAttribute[] = $createAttributes; } } if ($product['type'] === 'Variable') { $product_data = [ 'name' => isset($product['title']) ? $product['title'] : '', 'type' => 'variable', 'status' => 'publish', 'description' => isset($product['contentHTML']) ? $product['contentHTML'] : '', 'categories' => [ [ 'id' => $catID ] ], 'attributes' => $createAttribute, ]; } $products_data = $woocommerce->post('products', $product_data); if (is_countable($variations) && count($variations) > 0) { for ($v = 0; $v < count($variations); $v++) { $variant_images = $variations[$v]["imageSrcs"]; $variant_price = $variations[$v]["price"]; $variant_salePrice = $variations[$v]["priceCompareAt"]; $formatted_regular_price = number_format((float) $variant_price, 2, '.', ''); $formatted_selling_price = number_format((float) $variant_salePrice, 2, '.', ''); $seleVariation = array(); foreach($availableOptions as $availableOption){ for($i = 0; $i < count($attribute_ids); $i++){ $att_data = array( 'id' => $attribute_ids[$i], 'option' => $availableOption['optionValues'] ); $seleVariation[] = $att_data; } } $variation_data = [ 'regular_price' => $formatted_regular_price, 'sale_price' => $formatted_selling_price, 'attributes' => $seleVariation ]; $addVariations = $woocommerce->post('products/' . $products_data->id . '/variations', $variation_data); $variance_data = array( 'attributes' => $seleVariation ); $woocommerce->put('products/' . $products_data->id . '/variations/' . $addVariations->id, $variance_data); $stokeData = [ 'manage_stock' => true, 'stock_quantity' => isset($variations[$v]['quantity']) ? $variations[$v]['quantity'] : '', 'sku' => isset($variations[$v]['sku']) ? $variations[$v]['sku'] : '', ]; $woocommerce->put('products/' . $products_data->id . '/variations/' . $addVariations->id, $stokeData); } } } }
Now I am able to create simple and variable products. But In variable product, I am getting issues to create attributes and variations. I write code to save attribute globally. But when I Some how managed to create attributes inside variable products it takes all attributes from global attributes while each variable products have their attributr and variation in above json data and variation is also not assigning properly. I went through woocommerce docs, but it doesn’t help me. I am not getting where I am doing mistakes. can anyone help with my code?
- The topic ‘How to create Simple and Variable Products from JSON data?’ is closed to new replies.