Forum Replies Created

Viewing 1 replies (of 1 total)
  • Thread Starter devdigith

    (@devdigith)

    I modified the code, now issue is still same, I want to assign proper variation based on above json data. Problem is with variable product data. Just want to know where the coding wrong

    foreach ((array)$json_result as $product) {
        $variations = $product['variations'];
    
        $availableOptions = $product['availableOptions'];
        
    
        // 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'];
          }
        }
    
        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) {
          if ($product['type'] === 'Variable') {
            $attr_ids = [];
            $createAttribute = [];
            foreach ($availableOptions as $attributesOption) {
              $name = $attributesOption['optionName'];
              $values = $attributesOption['optionValues'];
              $at_id = $wpdb->get_var("select attribute_id from {$wpdb->prefix}woocommerce_attribute_taxonomies where attribute_name='" . $name . "'");
              if ($at_id != '' && $at_id > 0) {
                $attrID = $at_id;
              } else {
                try {
                  $attr_data = [
                    'name' => isset($name) ? $name : '',
                    'variation' => true,
                    'visible' => true,
                  ];
                  // Create the attribute without options for now
                  $attr_name = $woocommerce->post('products/attributes', $attr_data);
                  $attrID = $attr_name->id;
                } catch (Exception $e) {
                  // Handle the exception
                }
              }
              $attr_ids[] = $attrID;
              $createAttributes = array(
                'id' => $attrID,
                'variation' => True,
                'visible' => True,
                'options' => $values
              );
              $createAttribute[] = $createAttributes;
            }
    
            $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, '.', '');
    
                $variation_data = [
                  'regular_price' => $formatted_regular_price,
                  'sale_price' => $formatted_selling_price,
                  'attributes' => $createAttribute
                ];
                $addVariations = $woocommerce->post('products/' . $products_data->id . '/variations', $variation_data);
                $varData = array();
                $vv = [];
                foreach ($variations[$v]['options'] as $vOption) {
                  $atid = $wpdb->get_var("select attribute_id from {$wpdb->prefix}woocommerce_attribute_taxonomies where attribute_name='" . $vOption['name'] . "'");
                  $vv[] = $vOption['value'];
                  $vardata = array(
                    'id' => $atid,
                    'options' => $vv
                  );
                  $varData[] = $vardata;
                }
                $variance_data = array(
                  'attributes' => $varData
                );
    
                $woocommerce->put('products/' . $products_data->id . '/variations/' . $addVariations->id, $variance_data);
                echo '<pre>';
                print_r($varData);
                $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);
                
              }
            }
          }
        }
      }
    • This reply was modified 1 year, 1 month ago by devdigith.
Viewing 1 replies (of 1 total)