function wc_bulk_stock_after_process_qty_action($id)
 {
     global $sitepress;
     $new_quantity = get_post_meta($id, '_stock', true);
     if (is_numeric($new_quantity)) {
         $new_stock_status = $new_quantity > 0 ? "instock" : "outofstock";
         wc_update_product_stock_status($id, $new_stock_status);
         $trid = $sitepress->get_element_trid($id, 'post_product');
         if (is_numeric($trid)) {
             $translations = $sitepress->get_element_translations($trid, 'post_product');
             if (is_array($translations)) {
                 foreach ($translations as $translation) {
                     if (!isset($translation->element_id) || $translation->element_id == $id) {
                         continue;
                     }
                     update_post_meta($translation->element_id, '_stock', $new_quantity);
                     wc_update_product_stock_status($translation->element_id, $new_stock_status);
                 }
             }
         }
     }
 }
 /**
  * Sync variable product stock status with children.
  * @param  int $product_id
  */
 public static function sync_stock_status($product_id)
 {
     $children = get_posts(array('post_parent' => $product_id, 'posts_per_page' => -1, 'post_type' => 'product_variation', 'fields' => 'ids', 'post_status' => 'publish'));
     $stock_status = 'outofstock';
     foreach ($children as $child_id) {
         $child_stock_status = get_post_meta($child_id, '_stock_status', true);
         $child_stock_status = $child_stock_status ? $child_stock_status : 'instock';
         if ('instock' === $child_stock_status) {
             $stock_status = 'instock';
             break;
         }
     }
     wc_update_product_stock_status($product_id, $stock_status);
 }
 /**
  * Bulk edit
  * @param integer $post_id
  * @param WC_Product $product
  */
 public function bulk_edit_save($post_id, $product)
 {
     $old_regular_price = $product->regular_price;
     $old_sale_price = $product->sale_price;
     // Save fields
     if (!empty($_REQUEST['change_weight']) && isset($_REQUEST['_weight'])) {
         update_post_meta($post_id, '_weight', wc_clean(stripslashes($_REQUEST['_weight'])));
     }
     if (!empty($_REQUEST['change_dimensions'])) {
         if (isset($_REQUEST['_length'])) {
             update_post_meta($post_id, '_length', wc_clean(stripslashes($_REQUEST['_length'])));
         }
         if (isset($_REQUEST['_width'])) {
             update_post_meta($post_id, '_width', wc_clean(stripslashes($_REQUEST['_width'])));
         }
         if (isset($_REQUEST['_height'])) {
             update_post_meta($post_id, '_height', wc_clean(stripslashes($_REQUEST['_height'])));
         }
     }
     if (!empty($_REQUEST['_tax_status'])) {
         update_post_meta($post_id, '_tax_status', wc_clean($_REQUEST['_tax_status']));
     }
     if (!empty($_REQUEST['_tax_class'])) {
         $tax_class = wc_clean($_REQUEST['_tax_class']);
         if ('standard' == $tax_class) {
             $tax_class = '';
         }
         update_post_meta($post_id, '_tax_class', $tax_class);
     }
     if (!empty($_REQUEST['_stock_status'])) {
         $stock_status = wc_clean($_REQUEST['_stock_status']);
         if ($product->is_type('variable')) {
             foreach ($product->get_children() as $child_id) {
                 if ('yes' !== get_post_meta($child_id, '_manage_stock', true)) {
                     wc_update_product_stock_status($child_id, $stock_status);
                 }
             }
             WC_Product_Variable::sync_stock_status($post_id);
         } else {
             wc_update_product_stock_status($post_id, $stock_status);
         }
     }
     if (!empty($_REQUEST['_shipping_class'])) {
         $shipping_class = '_no_shipping_class' == $_REQUEST['_shipping_class'] ? '' : wc_clean($_REQUEST['_shipping_class']);
         wp_set_object_terms($post_id, $shipping_class, 'product_shipping_class');
     }
     if (!empty($_REQUEST['_visibility'])) {
         if (update_post_meta($post_id, '_visibility', wc_clean($_REQUEST['_visibility']))) {
             do_action('woocommerce_product_set_visibility', $post_id, wc_clean($_REQUEST['_visibility']));
         }
     }
     if (!empty($_REQUEST['_featured'])) {
         if (update_post_meta($post_id, '_featured', stripslashes($_REQUEST['_featured']))) {
             delete_transient('wc_featured_products');
         }
     }
     // Sold Individually
     if (!empty($_REQUEST['_sold_individually'])) {
         if ($_REQUEST['_sold_individually'] == 'yes') {
             update_post_meta($post_id, '_sold_individually', 'yes');
         } else {
             update_post_meta($post_id, '_sold_individually', '');
         }
     }
     // Handle price - remove dates and set to lowest
     if ($product->is_type('simple') || $product->is_type('external')) {
         $price_changed = false;
         if (!empty($_REQUEST['change_regular_price'])) {
             $change_regular_price = absint($_REQUEST['change_regular_price']);
             $regular_price = esc_attr(stripslashes($_REQUEST['_regular_price']));
             switch ($change_regular_price) {
                 case 1:
                     $new_price = $regular_price;
                     break;
                 case 2:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = $old_regular_price + round($old_regular_price * $percent, wc_get_price_decimals());
                     } else {
                         $new_price = $old_regular_price + $regular_price;
                     }
                     break;
                 case 3:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = max(0, $old_regular_price - round($old_regular_price * $percent, wc_get_price_decimals()));
                     } else {
                         $new_price = max(0, $old_regular_price - $regular_price);
                     }
                     break;
                 default:
                     break;
             }
             if (isset($new_price) && $new_price != $old_regular_price) {
                 $price_changed = true;
                 $new_price = round($new_price, wc_get_price_decimals());
                 update_post_meta($post_id, '_regular_price', $new_price);
                 $product->regular_price = $new_price;
             }
         }
         if (!empty($_REQUEST['change_sale_price'])) {
             $change_sale_price = absint($_REQUEST['change_sale_price']);
             $sale_price = esc_attr(stripslashes($_REQUEST['_sale_price']));
             switch ($change_sale_price) {
                 case 1:
                     $new_price = $sale_price;
                     break;
                 case 2:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = $old_sale_price + $old_sale_price * $percent;
                     } else {
                         $new_price = $old_sale_price + $sale_price;
                     }
                     break;
                 case 3:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = max(0, $old_sale_price - $old_sale_price * $percent);
                     } else {
                         $new_price = max(0, $old_sale_price - $sale_price);
                     }
                     break;
                 case 4:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = max(0, $product->regular_price - $product->regular_price * $percent);
                     } else {
                         $new_price = max(0, $product->regular_price - $sale_price);
                     }
                     break;
                 default:
                     break;
             }
             if (isset($new_price) && $new_price != $old_sale_price) {
                 $price_changed = true;
                 $new_price = !empty($new_price) || '0' === $new_price ? round($new_price, wc_get_price_decimals()) : '';
                 update_post_meta($post_id, '_sale_price', $new_price);
                 $product->sale_price = $new_price;
             }
         }
         if ($price_changed) {
             update_post_meta($post_id, '_sale_price_dates_from', '');
             update_post_meta($post_id, '_sale_price_dates_to', '');
             if ($product->regular_price < $product->sale_price) {
                 $product->sale_price = '';
                 update_post_meta($post_id, '_sale_price', '');
             }
             if ($product->sale_price) {
                 update_post_meta($post_id, '_price', $product->sale_price);
             } else {
                 update_post_meta($post_id, '_price', $product->regular_price);
             }
         }
     }
     // Handle stock
     if (!$product->is_type('grouped')) {
         if (!empty($_REQUEST['change_stock'])) {
             update_post_meta($post_id, '_manage_stock', 'yes');
             wc_update_product_stock($post_id, wc_stock_amount($_REQUEST['_stock']));
         }
         if (!empty($_REQUEST['_manage_stock'])) {
             if ($_REQUEST['_manage_stock'] == 'yes') {
                 update_post_meta($post_id, '_manage_stock', 'yes');
             } else {
                 update_post_meta($post_id, '_manage_stock', 'no');
                 wc_update_product_stock($post_id, 0);
             }
         }
         if (!empty($_REQUEST['_backorders'])) {
             update_post_meta($post_id, '_backorders', wc_clean($_REQUEST['_backorders']));
         }
     }
     do_action('woocommerce_product_bulk_edit_save', $product);
 }
Esempio n. 4
0
 /**
  * Some functions, like the term recount, require the visibility to be set prior. Lets save that here.
  *
  * @param int $post_id
  */
 public static function pre_post_update($post_id)
 {
     if (isset($_POST['_visibility'])) {
         if (update_post_meta($post_id, '_visibility', wc_clean($_POST['_visibility']))) {
             do_action('woocommerce_product_set_visibility', $post_id, wc_clean($_POST['_visibility']));
         }
     }
     if (isset($_POST['_stock_status'])) {
         wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
     }
 }
Esempio n. 5
0
 /**
  * Some functions, like the term recount, require the visibility to be set prior. Lets save that here.
  *
  * @param int $post_id
  */
 public static function pre_post_update($post_id)
 {
     if ('product' === get_post_type($post_id)) {
         $product_type = empty($_POST['product-type']) ? 'simple' : sanitize_title(stripslashes($_POST['product-type']));
         if (isset($_POST['_visibility'])) {
             if (update_post_meta($post_id, '_visibility', wc_clean($_POST['_visibility']))) {
                 do_action('woocommerce_product_set_visibility', $post_id, wc_clean($_POST['_visibility']));
             }
         }
         if (isset($_POST['_stock_status']) && 'variable' !== $product_type) {
             wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
         }
     }
 }
 /**
  * Save variations.
  *
  * @param WC_Product $product
  * @param WP_REST_Request $request
  * @return bool
  * @throws WC_REST_Exception
  */
 protected function save_variations_data($product, $request)
 {
     global $wpdb;
     $variations = $request['variations'];
     $attributes = $product->get_attributes();
     foreach ($variations as $menu_order => $variation) {
         $variation_id = isset($variation['id']) ? absint($variation['id']) : 0;
         // Generate a useful post title.
         $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), $variation_id, esc_html(get_the_title($product->id)));
         // Update or Add post.
         if (!$variation_id) {
             $post_status = isset($variation['visible']) && false === $variation['visible'] ? 'private' : 'publish';
             $new_variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $product->id, 'post_type' => 'product_variation', 'menu_order' => $menu_order);
             $variation_id = wp_insert_post($new_variation);
             do_action('woocommerce_create_product_variation', $variation_id);
         } else {
             $update_variation = array('post_title' => $variation_post_title, 'menu_order' => $menu_order);
             if (isset($variation['visible'])) {
                 $post_status = false === $variation['visible'] ? 'private' : 'publish';
                 $update_variation['post_status'] = $post_status;
             }
             $wpdb->update($wpdb->posts, $update_variation, array('ID' => $variation_id));
             do_action('woocommerce_update_product_variation', $variation_id);
         }
         // Stop with we don't have a variation ID.
         if (is_wp_error($variation_id)) {
             throw new WC_REST_Exception('woocommerce_rest_cannot_save_product_variation', $variation_id->get_error_message(), 400);
         }
         // SKU.
         if (isset($variation['sku'])) {
             $sku = get_post_meta($variation_id, '_sku', true);
             $new_sku = wc_clean($variation['sku']);
             if ('' === $new_sku) {
                 update_post_meta($variation_id, '_sku', '');
             } elseif ($new_sku !== $sku) {
                 if (!empty($new_sku)) {
                     $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku);
                     if (!$unique_sku) {
                         throw new WC_REST_Exception('woocommerce_rest_product_sku_already_exists', __('The SKU already exists on another product.', 'woocommerce'), 400);
                     } else {
                         update_post_meta($variation_id, '_sku', $new_sku);
                     }
                 } else {
                     update_post_meta($variation_id, '_sku', '');
                 }
             }
         }
         // Thumbnail.
         if (isset($variation['image']) && is_array($variation['image'])) {
             $image = current($variation['image']);
             if ($image && is_array($image)) {
                 if (isset($image['position']) && 0 === $image['position']) {
                     $attachment_id = isset($image['id']) ? absint($image['id']) : 0;
                     if (0 === $attachment_id && isset($image['src'])) {
                         $upload = wc_rest_upload_image_from_url(wc_clean($image['src']));
                         if (is_wp_error($upload)) {
                             throw new WC_REST_Exception('woocommerce_product_image_upload_error', $upload->get_error_message(), 400);
                         }
                         $attachment_id = wc_rest_set_uploaded_image_as_attachment($upload, $product->id);
                     }
                     // Set the image alt if present.
                     if (!empty($image['alt'])) {
                         update_post_meta($attachment_id, '_wp_attachment_image_alt', wc_clean($image['alt']));
                     }
                     // Set the image name if present.
                     if (!empty($image['name'])) {
                         wp_update_post(array('ID' => $attachment_id, 'post_title' => $image['name']));
                     }
                     update_post_meta($variation_id, '_thumbnail_id', $attachment_id);
                 }
             } else {
                 delete_post_meta($variation_id, '_thumbnail_id');
             }
         }
         // Virtual variation.
         if (isset($variation['virtual'])) {
             $is_virtual = true === $variation['virtual'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_virtual', $is_virtual);
         }
         // Downloadable variation.
         if (isset($variation['downloadable'])) {
             $is_downloadable = true === $variation['downloadable'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_downloadable', $is_downloadable);
         } else {
             $is_downloadable = get_post_meta($variation_id, '_downloadable', true);
         }
         // Shipping data.
         $this->save_product_shipping_data($variation_id, $variation);
         // Stock handling.
         if (isset($variation['manage_stock'])) {
             $manage_stock = true === $variation['manage_stock'] ? 'yes' : 'no';
         } else {
             $manage_stock = get_post_meta($variation_id, '_manage_stock', true);
         }
         update_post_meta($variation_id, '_manage_stock', '' === $manage_stock ? 'no' : $manage_stock);
         if (isset($variation['in_stock'])) {
             $stock_status = true === $variation['in_stock'] ? 'instock' : 'outofstock';
         } else {
             $stock_status = get_post_meta($variation_id, '_stock_status', true);
         }
         wc_update_product_stock_status($variation_id, '' === $stock_status ? 'instock' : $stock_status);
         if ('yes' === $manage_stock) {
             $backorders = get_post_meta($variation_id, '_backorders', true);
             if (isset($variation['backorders'])) {
                 $backorders = $variation['backorders'];
             }
             update_post_meta($variation_id, '_backorders', '' === $backorders ? 'no' : $backorders);
             if (isset($variation['stock_quantity'])) {
                 wc_update_product_stock($variation_id, wc_stock_amount($variation['stock_quantity']));
             } elseif (isset($request['inventory_delta'])) {
                 $stock_quantity = wc_stock_amount(get_post_meta($variation_id, '_stock', true));
                 $stock_quantity += wc_stock_amount($request['inventory_delta']);
                 wc_update_product_stock($variation_id, wc_stock_amount($stock_quantity));
             }
         } else {
             delete_post_meta($variation_id, '_backorders');
             delete_post_meta($variation_id, '_stock');
         }
         // Regular Price.
         if (isset($variation['regular_price'])) {
             $regular_price = '' === $variation['regular_price'] ? '' : $variation['regular_price'];
         } else {
             $regular_price = get_post_meta($variation_id, '_regular_price', true);
         }
         // Sale Price.
         if (isset($variation['sale_price'])) {
             $sale_price = '' === $variation['sale_price'] ? '' : $variation['sale_price'];
         } else {
             $sale_price = get_post_meta($variation_id, '_sale_price', true);
         }
         if (isset($variation['date_on_sale_from'])) {
             $date_from = $variation['date_on_sale_from'];
         } else {
             $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true);
             $date_from = '' === $date_from ? '' : date('Y-m-d', $date_from);
         }
         if (isset($variation['date_on_sale_to'])) {
             $date_to = $variation['date_on_sale_to'];
         } else {
             $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true);
             $date_to = '' === $date_to ? '' : date('Y-m-d', $date_to);
         }
         _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to);
         // Tax class.
         if (isset($variation['tax_class'])) {
             if ($variation['tax_class'] !== 'parent') {
                 update_post_meta($variation_id, '_tax_class', wc_clean($variation['tax_class']));
             } else {
                 delete_post_meta($variation_id, '_tax_class');
             }
         }
         // Downloads.
         if ('yes' === $is_downloadable) {
             // Downloadable files.
             if (isset($variation['downloads']) && is_array($variation['downloads'])) {
                 $this->save_downloadable_files($product->id, $variation['downloads'], $variation_id);
             }
             // Download limit.
             if (isset($variation['download_limit'])) {
                 update_post_meta($variation_id, '_download_limit', -1 === $variation['download_limit'] ? '' : absint($variation['download_limit']));
             }
             // Download expiry.
             if (isset($variation['download_expiry'])) {
                 update_post_meta($variation_id, '_download_expiry', -1 === $variation['download_expiry'] ? '' : absint($variation['download_expiry']));
             }
         } else {
             update_post_meta($variation_id, '_download_limit', '');
             update_post_meta($variation_id, '_download_expiry', '');
             update_post_meta($variation_id, '_downloadable_files', '');
         }
         // Description.
         if (isset($variation['description'])) {
             update_post_meta($variation_id, '_variation_description', wp_kses_post($variation['description']));
         }
         // Update taxonomies.
         if (isset($variation['attributes'])) {
             $updated_attribute_keys = array();
             foreach ($variation['attributes'] as $attribute) {
                 $attribute_id = 0;
                 $attribute_name = '';
                 // Check ID for global attributes or name for product attributes.
                 if (!empty($attribute['id'])) {
                     $attribute_id = absint($attribute['id']);
                     $attribute_name = wc_attribute_taxonomy_name_by_id($attribute_id);
                 } elseif (!empty($attribute['name'])) {
                     $attribute_name = sanitize_title($attribute['name']);
                 }
                 if (!$attribute_id && !$attribute_name) {
                     continue;
                 }
                 if (isset($attributes[$attribute_name])) {
                     $_attribute = $attributes[$attribute_name];
                 }
                 if (isset($_attribute['is_variation']) && $_attribute['is_variation']) {
                     $_attribute_key = 'attribute_' . sanitize_title($_attribute['name']);
                     $updated_attribute_keys[] = $_attribute_key;
                     if (isset($_attribute['is_taxonomy']) && $_attribute['is_taxonomy']) {
                         // Don't use wc_clean as it destroys sanitized characters
                         $_attribute_value = isset($attribute['option']) ? sanitize_title(stripslashes($attribute['option'])) : '';
                     } else {
                         $_attribute_value = isset($attribute['option']) ? wc_clean(stripslashes($attribute['option'])) : '';
                     }
                     update_post_meta($variation_id, $_attribute_key, $_attribute_value);
                 }
             }
             // Remove old taxonomies attributes so data is kept up to date - first get attribute key names.
             $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id));
             foreach ($delete_attribute_keys as $key) {
                 delete_post_meta($variation_id, $key);
             }
         }
         do_action('woocommerce_rest_save_product_variation', $variation_id, $menu_order, $variation);
     }
     // Update parent if variable so price sorting works and stays in sync with the cheapest child.
     WC_Product_Variable::sync($product->id);
     // Update default attributes options setting.
     if (isset($request['default_attribute'])) {
         $request['default_attributes'] = $request['default_attribute'];
     }
     if (isset($request['default_attributes']) && is_array($request['default_attributes'])) {
         $default_attributes = array();
         foreach ($request['default_attributes'] as $attribute) {
             $attribute_id = 0;
             $attribute_name = '';
             // Check ID for global attributes or name for product attributes.
             if (!empty($attribute['id'])) {
                 $attribute_id = absint($attribute['id']);
                 $attribute_name = wc_attribute_taxonomy_name_by_id($attribute_id);
             } elseif (!empty($attribute['name'])) {
                 $attribute_name = sanitize_title($attribute['name']);
             }
             if (!$attribute_id && !$attribute_name) {
                 continue;
             }
             if (isset($attributes[$attribute_name])) {
                 $_attribute = $attributes[$attribute_name];
                 if ($_attribute['is_variation']) {
                     $value = '';
                     if (isset($attribute['option'])) {
                         if ($_attribute['is_taxonomy']) {
                             // Don't use wc_clean as it destroys sanitized characters.
                             $value = sanitize_title(trim(stripslashes($attribute['option'])));
                         } else {
                             $value = wc_clean(trim(stripslashes($attribute['option'])));
                         }
                     }
                     if ($value) {
                         $default_attributes[$attribute_name] = $value;
                     }
                 }
             }
         }
         update_post_meta($product->id, '_default_attributes', $default_attributes);
     }
     return true;
 }
Esempio n. 7
0
function wc1c_replace_offer_post_meta($is_full, $post_id, $offer, $attributes = array())
{
    $price = isset($offer['Цена']['ЦенаЗаЕдиницу']) ? wc1c_parse_decimal($offer['Цена']['ЦенаЗаЕдиницу']) : null;
    if (!is_null($price)) {
        $coefficient = isset($offer['Цена']['Коэффициент']) ? wc1c_parse_decimal($offer['Цена']['Коэффициент']) : null;
        if (!is_null($coefficient)) {
            $price *= $coefficient;
        }
    }
    $post_meta = array();
    if (!is_null($price)) {
        $post_meta['_regular_price'] = $price;
        $post_meta['_manage_stock'] = 'yes';
    }
    if ($attributes) {
        foreach ($attributes as $attribute_name => $attribute_value) {
            $meta_key = 'attribute_' . sanitize_title($attribute_name);
            $post_meta[$meta_key] = $attribute_value;
        }
        $current_post_meta = get_post_meta($post_id);
        foreach ($current_post_meta as $meta_key => $meta_value) {
            $current_post_meta[$meta_key] = $meta_value[0];
        }
        foreach ($current_post_meta as $meta_key => $meta_value) {
            if (strpos($meta_key, 'attribute_') !== 0 || array_key_exists($meta_key, $post_meta)) {
                continue;
            }
            delete_post_meta($post_id, $meta_key);
        }
    }
    if (!is_null($price)) {
        $sale_price = @$current_post_meta['_sale_price'];
        $sale_price_from = @$current_post_meta['_sale_price_dates_from'];
        $sale_price_to = @$current_post_meta['_sale_price_dates_to'];
        if (empty($current_post_meta['_sale_price'])) {
            $post_meta['_price'] = $price;
        } else {
            if (empty($sale_price_from) && empty($sale_price_to)) {
                $post_meta['_price'] = $current_post_meta['_sale_price'];
            } else {
                $now = strtotime('now', current_time('timestamp'));
                if (!empty($sale_price_from) && strtotime($sale_price_from) < $now) {
                    $post_meta['_price'] = $current_post_meta['_sale_price'];
                }
                if (!empty($sale_price_to) && strtotime($sale_price_to) < $now) {
                    $post_meta['_price'] = $price;
                    $post_meta['_sale_price_dates_from'] = '';
                    $post_meta['_sale_price_dates_to'] = '';
                }
            }
        }
    }
    foreach ($post_meta as $meta_key => $meta_value) {
        $current_meta_value = @$current_post_meta[$meta_key];
        if ($meta_value !== '' && $current_meta_value == $meta_value) {
            continue;
        }
        if ($meta_value === '' && $current_meta_value === $meta_value) {
            continue;
        }
        update_post_meta($post_id, $meta_key, $meta_value);
    }
    $quantity = isset($offer['Количество']) ? $offer['Количество'] : @$offer['КоличествоНаСкладе'];
    if (!is_null($quantity)) {
        $quantity = wc1c_parse_decimal($quantity);
        wc_update_product_stock($post_id, $quantity);
        $stock_status = $quantity > 0 ? 'instock' : 'outofstock';
        @wc_update_product_stock_status($post_id, $stock_status);
    }
    do_action('wc1c_post_offer_meta', $post_id, $offer, $is_full);
}
Esempio n. 8
0
 /**
  * @see CACIE_Editable_Model::column_save()
  * @since 1.0
  */
 public function column_save($id, $column, $value)
 {
     global $wpdb;
     if (!($post = get_post($id))) {
         exit;
     }
     if (!current_user_can('edit_post', $id)) {
         exit;
     }
     // Third party columns can use the save() method as a callback for inline-editing
     // If a column features a saving method itself, the "return" statement makes sure default behaviour is prevented
     if (method_exists($column, 'save')) {
         $result = $column->save($id, $value);
         // Return a possible WP_Error yielded by the column save method
         if (is_wp_error($result)) {
             return $result;
         }
         return;
     }
     // Get editability data for the column to be saved
     $editable = $this->get_editable($column->properties->name);
     switch ($column->properties->type) {
         // Default
         case 'categories':
             $this->set_post_terms($id, $value, 'category');
             break;
         case 'date':
             // preserve the original time
             $time = strtotime("1970-01-01 " . date('H:i:s', strtotime($post->post_date)));
             wp_update_post(array('ID' => $post->ID, 'edit_date' => 1, 'post_date' => date('Y-m-d H:i:s', strtotime($value) + $time)));
             break;
         case 'tags':
             $this->set_post_terms($id, $value, 'post_tag');
             break;
             // Custom columns
         // Custom columns
         case 'column-acf_field':
             if (function_exists('update_field')) {
                 update_field($column->get_field_key(), $value, $post->ID);
             }
             break;
         case 'column-attachment':
             // detach
             if ($attachment_ids = get_posts(array('post_type' => 'attachment', 'post_parent' => $post->ID, 'posts_per_page' => -1, 'fields' => 'ids'))) {
                 foreach ($attachment_ids as $attachment_id) {
                     wp_update_post(array('ID' => $attachment_id, 'post_parent' => ''));
                 }
             }
             // attach
             if (!empty($value)) {
                 foreach ($value as $attachment_id) {
                     wp_update_post(array('ID' => $attachment_id, 'post_parent' => $post->ID));
                 }
             }
             break;
         case 'column-featured_image':
         case 'thumb':
             // woocommerce
             if ($value) {
                 set_post_thumbnail($post->ID, $value);
             } else {
                 delete_post_thumbnail($post);
             }
             break;
         case 'column-meta':
             $this->update_meta($post->ID, $column->get_field_key(), $value);
             break;
         case 'column-page_template':
             update_post_meta($post->ID, '_wp_page_template', $value);
             break;
         case 'column-post_formats':
             set_post_format($post->ID, $value);
             break;
         case 'column-sticky':
             if ('yes' == $value) {
                 stick_post($post->ID);
             } else {
                 unstick_post($post->ID);
             }
             break;
         case 'column-taxonomy':
             if (!empty($column->options->taxonomy) && taxonomy_exists($column->options->taxonomy)) {
                 if ('post_format' == $column->options->taxonomy && !empty($value)) {
                     $value = $value[0];
                 }
                 $this->set_post_terms($id, $value, $column->options->taxonomy);
             }
             break;
             /**
              * WooCommerce Columns
              *
              */
         /**
          * WooCommerce Columns
          *
          */
         case 'price':
             if (is_array($value) && isset($value['regular_price']) && isset($value['sale_price']) && isset($value['sale_price_dates_from']) && isset($value['sale_price_dates_to'])) {
                 CACIE_WooCommerce::update_product_pricing($post->ID, array('regular_price' => $value['regular_price'], 'sale_price' => $value['sale_price'], 'sale_price_dates_from' => $value['sale_price_dates_from'], 'sale_price_dates_to' => $value['sale_price_dates_to']));
             }
             break;
         case 'column-wc-weight':
             $product = get_product($post->ID);
             if (!$product->is_virtual()) {
                 update_post_meta($post->ID, '_weight', $value === '' ? '' : wc_format_decimal($value));
             }
             break;
         case 'column-wc-dimensions':
             if (is_array($value) && isset($value['length']) && isset($value['width']) && isset($value['height'])) {
                 $product = get_product($post->ID);
                 if (!$product->is_virtual()) {
                     update_post_meta($post->ID, '_length', $value === '' ? '' : wc_format_decimal($value['length']));
                     update_post_meta($post->ID, '_width', $value === '' ? '' : wc_format_decimal($value['width']));
                     update_post_meta($post->ID, '_height', $value === '' ? '' : wc_format_decimal($value['height']));
                 }
             }
             break;
         case 'sku':
             $product = get_product($post->ID);
             $current_sku = get_post_meta($post->ID, '_sku', true);
             $new_sku = wc_clean($value);
             if (empty($new_sku)) {
                 $new_sku = '';
             }
             if ($new_sku != $current_sku) {
                 $existing_id = $wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\tSELECT {$wpdb->posts}.ID\n\t\t\t\t\t    FROM {$wpdb->posts}\n\t\t\t\t\t    LEFT JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)\n\t\t\t\t\t    WHERE {$wpdb->posts}.post_type = 'product'\n\t\t\t\t\t    AND {$wpdb->posts}.post_status = 'publish'\n\t\t\t\t\t    AND {$wpdb->postmeta}.meta_key = '_sku' AND {$wpdb->postmeta}.meta_value = %s\n\t\t\t\t\t", $new_sku));
                 if ($existing_id) {
                     return new WP_Error('cacie_error_sku_exists', __('The SKU must be unique.', 'cpac'));
                 }
                 update_post_meta($post->ID, '_sku', $new_sku);
             }
             break;
         case 'is_in_stock':
             if (get_option('woocommerce_manage_stock') == 'yes') {
                 if ($value['manage_stock'] == 'yes') {
                     update_post_meta($post->ID, '_manage_stock', 'yes');
                     wc_update_product_stock_status($post->ID, wc_clean($value['stock_status']));
                     wc_update_product_stock($post->ID, intval($value['stock']));
                 } else {
                     // Don't manage stock
                     update_post_meta($post->ID, '_manage_stock', 'no');
                     update_post_meta($post->ID, '_stock', '');
                     wc_update_product_stock_status($post->ID, wc_clean($value['stock_status']));
                 }
             } else {
                 wc_update_product_stock_status($post->ID, wc_clean($value['stock_status']));
             }
             break;
         case 'column-wc-stock-status':
             wc_update_product_stock_status($post->ID, wc_clean($value));
             break;
         case 'column-wc-free_shipping':
             update_post_meta($id, 'free_shipping', $value == 'yes' ? 'yes' : 'no');
             break;
         case 'column-wc-shipping_class':
             $this->set_post_terms($id, $value, 'product_shipping_class');
             break;
         case 'column-wc-apply_before_tax':
             update_post_meta($id, 'apply_before_tax', $value == 'yes' ? 'yes' : 'no');
             break;
         case 'column-wc-backorders_allowed':
             if (in_array($value, array('no', 'yes', 'notify'))) {
                 update_post_meta($post->ID, '_backorders', $value);
             }
             break;
         case 'column-wc-upsells':
             $upsell_ids = array();
             if (is_array($value)) {
                 foreach ($value as $upsell_id) {
                     if ($upsell_id && $upsell_id > 0) {
                         $upsell_ids[] = $upsell_id;
                     }
                 }
             }
             update_post_meta($id, '_upsell_ids', $upsell_ids);
             break;
         case 'column-wc-crosssells':
             $crosssell_ids = array();
             if (is_array($value)) {
                 foreach ($value as $crosssell_id) {
                     if ($crosssell_id && $crosssell_id > 0) {
                         $crosssell_ids[] = $crosssell_id;
                     }
                 }
             }
             update_post_meta($id, '_crosssell_ids', $crosssell_ids);
             break;
         case 'column-wc-exclude_products':
             $product_ids = array();
             if (is_array($value)) {
                 foreach ($value as $product_id) {
                     if ($product_id && $product_id > 0) {
                         $product_ids[] = $product_id;
                     }
                 }
             }
             update_post_meta($id, 'exclude_product_ids', implode(',', $product_ids));
             break;
         case 'column-wc-include_products':
             $product_ids = array();
             if (is_array($value)) {
                 foreach ($value as $product_id) {
                     if ($product_id && $product_id > 0) {
                         $product_ids[] = $product_id;
                     }
                 }
             }
             update_post_meta($id, 'product_ids', implode(',', $product_ids));
             break;
         case 'column-wc-minimum_amount':
             update_post_meta($id, 'minimum_amount', wc_format_decimal($value));
             break;
         case 'order_status':
             $order = new WC_Order($id);
             $order->update_status($value);
             break;
         case 'usage':
             update_post_meta($id, 'usage_limit', wc_clean($value['usage_limit']));
             update_post_meta($id, 'usage_limit_per_user', wc_clean($value['usage_limit_per_user']));
             break;
         case 'amount':
             update_post_meta($id, 'coupon_amount', wc_format_decimal($value));
             break;
         case 'type':
             update_post_meta($id, 'discount_type', wc_clean($value));
             break;
         case 'product_cat':
             $this->set_post_terms($id, $value, 'product_cat');
             break;
         case 'product_tag':
             $this->set_post_terms($id, $value, 'product_tag');
             break;
         case 'column-wc-featured':
             update_post_meta($id, '_featured', $value);
             break;
         case 'column-wc-visibility':
             update_post_meta($id, '_visibility', $value);
             break;
             // Save basic property such as title or description (data that is available in WP_Post)
         // Save basic property such as title or description (data that is available in WP_Post)
         default:
             if (!empty($editable['property'])) {
                 $property = $editable['property'];
                 if (isset($post->{$property})) {
                     wp_update_post(array('ID' => $post->ID, $property => $value));
                 }
             } else {
                 $result = null;
                 /**
                  * Called when a column is saved, but the saving is not handled by Admin Columns core
                  * This should be used for saving columns that are editable but do not have their own CPAC_Column class
                  * The first parameter, $result, should only be used if an error occurs
                  *
                  * @since 3.4
                  *
                  * @param WP_Error $result Result of saving
                  * @param CPAC_Column $column Column object
                  * @param int $id ID of item to be saved
                  * @param mixed $value Value to be saved
                  * @param CACIE_Editable_Model $model Editability storage model
                  */
                 $result = apply_filters('cac/editable/column_save', $result, $column, $id, $value, $this);
                 $result = apply_filters('cac/editable/column_save/column=' . $column->get_type(), $result, $column, $id, $value, $this);
                 if (is_wp_error($result)) {
                     return $result;
                 }
             }
     }
 }
 /**
  * Save product meta
  *
  * @since 2.2
  * @param int $id
  * @param array $data
  * @return bool|WP_Error
  */
 protected function save_product_meta($id, $data)
 {
     // Product Type
     $product_type = null;
     if (isset($data['type'])) {
         $product_type = wc_clean($data['type']);
         wp_set_object_terms($id, $product_type, 'product_type');
     } else {
         $_product_type = get_the_terms($id, 'product_type');
         if (is_array($_product_type)) {
             $_product_type = current($_product_type);
             $product_type = $_product_type->slug;
         }
     }
     // Virtual
     if (isset($data['virtual'])) {
         update_post_meta($id, '_virtual', true === $data['virtual'] ? 'yes' : 'no');
     }
     // Tax status
     if (isset($data['tax_status'])) {
         update_post_meta($id, '_tax_status', wc_clean($data['tax_status']));
     }
     // Tax Class
     if (isset($data['tax_class'])) {
         update_post_meta($id, '_tax_class', wc_clean($data['tax_class']));
     }
     // Catalog Visibility
     if (isset($data['catalog_visibility'])) {
         update_post_meta($id, '_visibility', wc_clean($data['catalog_visibility']));
     }
     // Purchase Note
     if (isset($data['purchase_note'])) {
         update_post_meta($id, '_purchase_note', wc_clean($data['purchase_note']));
     }
     // Featured Product
     if (isset($data['featured'])) {
         update_post_meta($id, '_featured', true === $data['featured'] ? 'yes' : 'no');
     }
     // Shipping data
     $this->save_product_shipping_data($id, $data);
     // SKU
     if (isset($data['sku'])) {
         $sku = get_post_meta($id, '_sku', true);
         $new_sku = wc_clean($data['sku']);
         if ('' == $new_sku) {
             update_post_meta($id, '_sku', '');
         } elseif ($new_sku !== $sku) {
             if (!empty($new_sku)) {
                 $unique_sku = wc_product_has_unique_sku($id, $new_sku);
                 if (!$unique_sku) {
                     return new WP_Error('woocommerce_api_product_sku_already_exists', __('The SKU already exists on another product', 'woocommerce'), array('status' => 400));
                 } else {
                     update_post_meta($id, '_sku', $new_sku);
                 }
             } else {
                 update_post_meta($id, '_sku', '');
             }
         }
     }
     // Attributes
     if (isset($data['attributes'])) {
         $attributes = array();
         foreach ($data['attributes'] as $attribute) {
             $is_taxonomy = 0;
             if (!isset($attribute['name'])) {
                 continue;
             }
             $taxonomy = $this->get_attribute_taxonomy_by_label($attribute['name']);
             if ($taxonomy) {
                 $is_taxonomy = 1;
             }
             if ($is_taxonomy) {
                 if (isset($attribute['options'])) {
                     // Select based attributes - Format values (posted values are slugs)
                     if (is_array($attribute['options'])) {
                         $values = array_map('sanitize_title', $attribute['options']);
                         // Text based attributes - Posted values are term names - don't change to slugs
                     } else {
                         $values = array_map('stripslashes', array_map('strip_tags', explode(WC_DELIMITER, $attribute['options'])));
                     }
                     $values = array_filter($values, 'strlen');
                 } else {
                     $values = array();
                 }
                 // Update post terms
                 if (taxonomy_exists($taxonomy)) {
                     wp_set_object_terms($id, $values, $taxonomy);
                 }
                 if ($values) {
                     // Add attribute to array, but don't set values
                     $attributes[$taxonomy] = array('name' => $taxonomy, 'value' => '', 'position' => isset($attribute['position']) ? absint($attribute['position']) : 0, 'is_visible' => isset($attribute['position']) && $attribute['position'] ? 1 : 0, 'is_variation' => isset($attribute['variation']) && $attribute['variation'] ? 1 : 0, 'is_taxonomy' => $is_taxonomy);
                 }
             } elseif (isset($attribute['options'])) {
                 // Array based
                 if (is_array($attribute['options'])) {
                     $values = implode(' ' . WC_DELIMITER . ' ', array_map('wc_clean', $attribute['options']));
                     // Text based, separate by pipe
                 } else {
                     $values = implode(' ' . WC_DELIMITER . ' ', array_map('wc_clean', explode(WC_DELIMITER, $attribute['options'])));
                 }
                 // Custom attribute - Add attribute to array and set the values
                 $attributes[sanitize_title($attribute['name'])] = array('name' => wc_clean($attribute['name']), 'value' => $values, 'position' => isset($attribute['position']) ? absint($attribute['position']) : 0, 'is_visible' => isset($attribute['position']) && $attribute['position'] ? 1 : 0, 'is_variation' => isset($attribute['variation']) && $attribute['variation'] ? 1 : 0, 'is_taxonomy' => $is_taxonomy);
             }
         }
         if (!function_exists('attributes_cmp')) {
             function attributes_cmp($a, $b)
             {
                 if ($a['position'] == $b['position']) {
                     return 0;
                 }
                 return $a['position'] < $b['position'] ? -1 : 1;
             }
         }
         uasort($attributes, 'attributes_cmp');
         update_post_meta($id, '_product_attributes', $attributes);
     }
     // Sales and prices
     if (in_array($product_type, array('variable', 'grouped'))) {
         // Variable and grouped products have no prices
         update_post_meta($id, '_regular_price', '');
         update_post_meta($id, '_sale_price', '');
         update_post_meta($id, '_sale_price_dates_from', '');
         update_post_meta($id, '_sale_price_dates_to', '');
         update_post_meta($id, '_price', '');
     } else {
         // Regular Price
         if (isset($data['regular_price'])) {
             $regular_price = '' === $data['regular_price'] ? '' : wc_format_decimal($data['regular_price']);
             update_post_meta($id, '_regular_price', $regular_price);
         } else {
             $regular_price = get_post_meta($id, '_regular_price', true);
         }
         // Sale Price
         if (isset($data['sale_price'])) {
             $sale_price = '' === $data['sale_price'] ? '' : wc_format_decimal($data['sale_price']);
             update_post_meta($id, '_sale_price', $sale_price);
         } else {
             $sale_price = get_post_meta($id, '_sale_price', true);
         }
         $date_from = isset($data['sale_price_dates_from']) ? $data['sale_price_dates_from'] : get_post_meta($id, '_sale_price_dates_from', true);
         $date_to = isset($data['sale_price_dates_to']) ? $data['sale_price_dates_to'] : get_post_meta($id, '_sale_price_dates_to', true);
         // Dates
         if ($date_from) {
             update_post_meta($id, '_sale_price_dates_from', strtotime($date_from));
         } else {
             update_post_meta($id, '_sale_price_dates_from', '');
         }
         if ($date_to) {
             update_post_meta($id, '_sale_price_dates_to', strtotime($date_to));
         } else {
             update_post_meta($id, '_sale_price_dates_to', '');
         }
         if ($date_to && !$date_from) {
             update_post_meta($id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
         }
         // Update price if on sale
         if ('' !== $sale_price && '' == $date_to && '' == $date_from) {
             update_post_meta($id, '_price', wc_format_decimal($sale_price));
         } else {
             update_post_meta($id, '_price', $regular_price);
         }
         if ('' !== $sale_price && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($id, '_price', wc_format_decimal($sale_price));
         }
         if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($id, '_price', $regular_price);
             update_post_meta($id, '_sale_price_dates_from', '');
             update_post_meta($id, '_sale_price_dates_to', '');
         }
     }
     // Update parent if grouped so price sorting works and stays in sync with the cheapest child
     $_product = wc_get_product($id);
     if ($_product->post->post_parent > 0 || $product_type == 'grouped') {
         $clear_parent_ids = array();
         if ($_product->post->post_parent > 0) {
             $clear_parent_ids[] = $_product->post->post_parent;
         }
         if ($product_type == 'grouped') {
             $clear_parent_ids[] = $id;
         }
         if ($clear_parent_ids) {
             foreach ($clear_parent_ids as $clear_id) {
                 $children_by_price = get_posts(array('post_parent' => $clear_id, 'orderby' => 'meta_value_num', 'order' => 'asc', 'meta_key' => '_price', 'posts_per_page' => 1, 'post_type' => 'product', 'fields' => 'ids'));
                 if ($children_by_price) {
                     foreach ($children_by_price as $child) {
                         $child_price = get_post_meta($child, '_price', true);
                         update_post_meta($clear_id, '_price', $child_price);
                     }
                 }
             }
         }
     }
     // Sold Individually
     if (isset($data['sold_individually'])) {
         update_post_meta($id, '_sold_individually', true === $data['sold_individually'] ? 'yes' : '');
     }
     // Stock status
     if (isset($data['in_stock'])) {
         $stock_status = true === $data['in_stock'] ? 'instock' : 'outofstock';
     } else {
         $stock_status = get_post_meta($id, '_stock_status', true);
         if ('' === $stock_status) {
             $stock_status = 'instock';
         }
     }
     // Stock Data
     if ('yes' == get_option('woocommerce_manage_stock')) {
         // Manage stock
         if (isset($data['managing_stock'])) {
             $managing_stock = true === $data['managing_stock'] ? 'yes' : 'no';
             update_post_meta($id, '_manage_stock', $managing_stock);
         } else {
             $managing_stock = get_post_meta($id, '_manage_stock', true);
         }
         // Backorders
         if (isset($data['backorders'])) {
             if ('notify' == $data['backorders']) {
                 $backorders = 'notify';
             } else {
                 $backorders = true === $data['backorders'] ? 'yes' : 'no';
             }
             update_post_meta($id, '_backorders', $backorders);
         } else {
             $backorders = get_post_meta($id, '_backorders', true);
         }
         if ('grouped' == $product_type) {
             update_post_meta($id, '_manage_stock', 'no');
             update_post_meta($id, '_backorders', 'no');
             update_post_meta($id, '_stock', '');
             wc_update_product_stock_status($id, $stock_status);
         } elseif ('external' == $product_type) {
             update_post_meta($id, '_manage_stock', 'no');
             update_post_meta($id, '_backorders', 'no');
             update_post_meta($id, '_stock', '');
             wc_update_product_stock_status($id, 'instock');
         } elseif ('yes' == $managing_stock) {
             update_post_meta($id, '_backorders', $backorders);
             wc_update_product_stock_status($id, $stock_status);
             // Stock quantity
             if (isset($data['stock_quantity'])) {
                 wc_update_product_stock($id, intval($data['stock_quantity']));
             }
         } else {
             // Don't manage stock
             update_post_meta($id, '_manage_stock', 'no');
             update_post_meta($id, '_backorders', $backorders);
             update_post_meta($id, '_stock', '');
             wc_update_product_stock_status($id, $stock_status);
         }
     } else {
         wc_update_product_stock_status($id, $stock_status);
     }
     // Upsells
     if (isset($data['upsell_ids'])) {
         $upsells = array();
         $ids = $data['upsell_ids'];
         if (!empty($ids)) {
             foreach ($ids as $id) {
                 if ($id && $id > 0) {
                     $upsells[] = $id;
                 }
             }
             update_post_meta($id, '_upsell_ids', $upsells);
         } else {
             delete_post_meta($id, '_upsell_ids');
         }
     }
     // Cross sells
     if (isset($data['cross_sell_ids'])) {
         $crosssells = array();
         $ids = $data['cross_sell_ids'];
         if (!empty($ids)) {
             foreach ($ids as $id) {
                 if ($id && $id > 0) {
                     $crosssells[] = $id;
                 }
             }
             update_post_meta($id, '_crosssell_ids', $crosssells);
         } else {
             delete_post_meta($id, '_crosssell_ids');
         }
     }
     // Product categories
     if (isset($data['categories']) && is_array($data['categories'])) {
         $terms = array_map('wc_clean', $data['categories']);
         wp_set_object_terms($id, $terms, 'product_cat');
     }
     // Product tags
     if (isset($data['tags']) && is_array($data['tags'])) {
         $terms = array_map('wc_clean', $data['tags']);
         wp_set_object_terms($id, $terms, 'product_tag');
     }
     // Downloadable
     if (isset($data['downloadable'])) {
         $is_downloadable = true === $data['downloadable'] ? 'yes' : 'no';
         update_post_meta($id, '_downloadable', $is_downloadable);
     } else {
         $is_downloadable = get_post_meta($id, '_downloadable', true);
     }
     // Downloadable options
     if ('yes' == $is_downloadable) {
         // Downloadable files
         if (isset($data['downloads']) && is_array($data['downloads'])) {
             $this->save_downloadable_files($id, $data['downloads']);
         }
         // Download limit
         if (isset($data['download_limit'])) {
             $download_limit = absint($data['download_limit']);
             update_post_meta($id, '_download_limit', !$download_limit ? '' : $download_limit);
         }
         // Download expiry
         if (isset($data['download_expiry'])) {
             $download_expiry = absint($data['download_expiry']);
             update_post_meta($id, '_download_expiry', !$download_expiry ? '' : $download_expiry);
         }
         // Download type
         if (isset($data['download_type'])) {
             update_post_meta($id, '_download_type', wc_clean($data['download_type']));
         }
     }
     // Product url
     if ($product_type == 'external') {
         if (isset($data['product_url'])) {
             update_post_meta($id, '_product_url', wc_clean($data['product_url']));
         }
         if (isset($data['button_text'])) {
             update_post_meta($id, '_button_text', wc_clean($data['button_text']));
         }
     }
     // Do action for product type
     do_action('woocommerce_api_process_product_meta_' . $product_type, $id, $data);
     return true;
 }
 /**
  * Save meta box data
  */
 public static function save($post_id, $post)
 {
     global $wpdb;
     // Add any default post meta
     add_post_meta($post_id, 'total_sales', '0', true);
     // Get types
     $product_type = empty($_POST['product-type']) ? 'simple' : sanitize_title(stripslashes($_POST['product-type']));
     $is_downloadable = isset($_POST['_downloadable']) ? 'yes' : 'no';
     $is_virtual = isset($_POST['_virtual']) ? 'yes' : 'no';
     // Product type + Downloadable/Virtual
     wp_set_object_terms($post_id, $product_type, 'product_type');
     update_post_meta($post_id, '_downloadable', $is_downloadable);
     update_post_meta($post_id, '_virtual', $is_virtual);
     // Update post meta
     if (isset($_POST['_regular_price'])) {
         update_post_meta($post_id, '_regular_price', $_POST['_regular_price'] === '' ? '' : wc_format_decimal($_POST['_regular_price']));
     }
     if (isset($_POST['_sale_price'])) {
         update_post_meta($post_id, '_sale_price', $_POST['_sale_price'] === '' ? '' : wc_format_decimal($_POST['_sale_price']));
     }
     if (isset($_POST['_tax_status'])) {
         update_post_meta($post_id, '_tax_status', stripslashes($_POST['_tax_status']));
     }
     if (isset($_POST['_tax_class'])) {
         update_post_meta($post_id, '_tax_class', stripslashes($_POST['_tax_class']));
     }
     if (isset($_POST['_visibility'])) {
         update_post_meta($post_id, '_visibility', stripslashes($_POST['_visibility']));
     }
     if (isset($_POST['_purchase_note'])) {
         update_post_meta($post_id, '_purchase_note', stripslashes($_POST['_purchase_note']));
     }
     update_post_meta($post_id, '_featured', isset($_POST['_featured']) ? 'yes' : 'no');
     // Dimensions
     if ($is_virtual == 'no') {
         if (isset($_POST['_weight'])) {
             update_post_meta($post_id, '_weight', $_POST['_weight'] === '' ? '' : wc_format_decimal($_POST['_weight']));
         }
         if (isset($_POST['_length'])) {
             update_post_meta($post_id, '_length', $_POST['_length'] === '' ? '' : wc_format_decimal($_POST['_length']));
         }
         if (isset($_POST['_width'])) {
             update_post_meta($post_id, '_width', $_POST['_width'] === '' ? '' : wc_format_decimal($_POST['_width']));
         }
         if (isset($_POST['_height'])) {
             update_post_meta($post_id, '_height', $_POST['_height'] === '' ? '' : wc_format_decimal($_POST['_height']));
         }
     } else {
         update_post_meta($post_id, '_weight', '');
         update_post_meta($post_id, '_length', '');
         update_post_meta($post_id, '_width', '');
         update_post_meta($post_id, '_height', '');
     }
     // Save shipping class
     $product_shipping_class = $_POST['product_shipping_class'] > 0 && $product_type != 'external' ? absint($_POST['product_shipping_class']) : '';
     wp_set_object_terms($post_id, $product_shipping_class, 'product_shipping_class');
     // Unique SKU
     $sku = get_post_meta($post_id, '_sku', true);
     $new_sku = wc_clean(stripslashes($_POST['_sku']));
     if ($new_sku == '') {
         update_post_meta($post_id, '_sku', '');
     } elseif ($new_sku !== $sku) {
         if (!empty($new_sku)) {
             if ($wpdb->get_var($wpdb->prepare("\n\t\t\t\t\t\tSELECT {$wpdb->posts}.ID\n\t\t\t\t\t    FROM {$wpdb->posts}\n\t\t\t\t\t    LEFT JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id)\n\t\t\t\t\t    WHERE {$wpdb->posts}.post_type = 'product'\n\t\t\t\t\t    AND {$wpdb->posts}.post_status = 'publish'\n\t\t\t\t\t    AND {$wpdb->postmeta}.meta_key = '_sku' AND {$wpdb->postmeta}.meta_value = '%s'\n\t\t\t\t\t ", $new_sku))) {
                 WC_Admin_Meta_Boxes::add_error(__('Product SKU must be unique.', 'woocommerce'));
             } else {
                 update_post_meta($post_id, '_sku', $new_sku);
             }
         } else {
             update_post_meta($post_id, '_sku', '');
         }
     }
     // Save Attributes
     $attributes = array();
     if (isset($_POST['attribute_names']) && isset($_POST['attribute_values'])) {
         $attribute_names = $_POST['attribute_names'];
         $attribute_values = $_POST['attribute_values'];
         if (isset($_POST['attribute_visibility'])) {
             $attribute_visibility = $_POST['attribute_visibility'];
         }
         if (isset($_POST['attribute_variation'])) {
             $attribute_variation = $_POST['attribute_variation'];
         }
         $attribute_is_taxonomy = $_POST['attribute_is_taxonomy'];
         $attribute_position = $_POST['attribute_position'];
         $attribute_names_count = sizeof($attribute_names);
         for ($i = 0; $i < $attribute_names_count; $i++) {
             if (!$attribute_names[$i]) {
                 continue;
             }
             $is_visible = isset($attribute_visibility[$i]) ? 1 : 0;
             $is_variation = isset($attribute_variation[$i]) ? 1 : 0;
             $is_taxonomy = $attribute_is_taxonomy[$i] ? 1 : 0;
             if ($is_taxonomy) {
                 if (isset($attribute_values[$i])) {
                     // Select based attributes - Format values (posted values are slugs)
                     if (is_array($attribute_values[$i])) {
                         $values = array_map('sanitize_title', $attribute_values[$i]);
                         // Text based attributes - Posted values are term names - don't change to slugs
                     } else {
                         $values = array_map('stripslashes', array_map('strip_tags', explode(WC_DELIMITER, $attribute_values[$i])));
                     }
                     // Remove empty items in the array
                     $values = array_filter($values, 'strlen');
                 } else {
                     $values = array();
                 }
                 // Update post terms
                 if (taxonomy_exists($attribute_names[$i])) {
                     wp_set_object_terms($post_id, $values, $attribute_names[$i]);
                 }
                 if ($values) {
                     // Add attribute to array, but don't set values
                     $attributes[sanitize_title($attribute_names[$i])] = array('name' => wc_clean($attribute_names[$i]), 'value' => '', 'position' => $attribute_position[$i], 'is_visible' => $is_visible, 'is_variation' => $is_variation, 'is_taxonomy' => $is_taxonomy);
                 }
             } elseif (isset($attribute_values[$i])) {
                 // Text based, separate by pipe
                 $values = implode(' ' . WC_DELIMITER . ' ', array_map('wc_clean', explode(WC_DELIMITER, $attribute_values[$i])));
                 // Custom attribute - Add attribute to array and set the values
                 $attributes[sanitize_title($attribute_names[$i])] = array('name' => wc_clean($attribute_names[$i]), 'value' => $values, 'position' => $attribute_position[$i], 'is_visible' => $is_visible, 'is_variation' => $is_variation, 'is_taxonomy' => $is_taxonomy);
             }
         }
     }
     if (!function_exists('attributes_cmp')) {
         function attributes_cmp($a, $b)
         {
             if ($a['position'] == $b['position']) {
                 return 0;
             }
             return $a['position'] < $b['position'] ? -1 : 1;
         }
     }
     uasort($attributes, 'attributes_cmp');
     update_post_meta($post_id, '_product_attributes', $attributes);
     // Sales and prices
     if (in_array($product_type, array('variable', 'grouped'))) {
         // Variable and grouped products have no prices
         update_post_meta($post_id, '_regular_price', '');
         update_post_meta($post_id, '_sale_price', '');
         update_post_meta($post_id, '_sale_price_dates_from', '');
         update_post_meta($post_id, '_sale_price_dates_to', '');
         update_post_meta($post_id, '_price', '');
     } else {
         $date_from = isset($_POST['_sale_price_dates_from']) ? $_POST['_sale_price_dates_from'] : '';
         $date_to = isset($_POST['_sale_price_dates_to']) ? $_POST['_sale_price_dates_to'] : '';
         // Dates
         if ($date_from) {
             update_post_meta($post_id, '_sale_price_dates_from', strtotime($date_from));
         } else {
             update_post_meta($post_id, '_sale_price_dates_from', '');
         }
         if ($date_to) {
             update_post_meta($post_id, '_sale_price_dates_to', strtotime($date_to));
         } else {
             update_post_meta($post_id, '_sale_price_dates_to', '');
         }
         if ($date_to && !$date_from) {
             update_post_meta($post_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
         }
         // Update price if on sale
         if ($_POST['_sale_price'] !== '' && $date_to == '' && $date_from == '') {
             update_post_meta($post_id, '_price', wc_format_decimal($_POST['_sale_price']));
         } else {
             update_post_meta($post_id, '_price', $_POST['_regular_price'] === '' ? '' : wc_format_decimal($_POST['_regular_price']));
         }
         if ($_POST['_sale_price'] !== '' && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($post_id, '_price', wc_format_decimal($_POST['_sale_price']));
         }
         if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($post_id, '_price', $_POST['_regular_price'] === '' ? '' : wc_format_decimal($_POST['_regular_price']));
             update_post_meta($post_id, '_sale_price_dates_from', '');
             update_post_meta($post_id, '_sale_price_dates_to', '');
         }
     }
     // Update parent if grouped so price sorting works and stays in sync with the cheapest child
     if ($post->post_parent > 0 || $product_type == 'grouped' || $_POST['previous_parent_id'] > 0) {
         $clear_parent_ids = array();
         if ($post->post_parent > 0) {
             $clear_parent_ids[] = $post->post_parent;
         }
         if ($product_type == 'grouped') {
             $clear_parent_ids[] = $post_id;
         }
         if ($_POST['previous_parent_id'] > 0) {
             $clear_parent_ids[] = absint($_POST['previous_parent_id']);
         }
         if ($clear_parent_ids) {
             foreach ($clear_parent_ids as $clear_id) {
                 $children_by_price = get_posts(array('post_parent' => $clear_id, 'orderby' => 'meta_value_num', 'order' => 'asc', 'meta_key' => '_price', 'posts_per_page' => 1, 'post_type' => 'product', 'fields' => 'ids'));
                 if ($children_by_price) {
                     foreach ($children_by_price as $child) {
                         $child_price = get_post_meta($child, '_price', true);
                         update_post_meta($clear_id, '_price', $child_price);
                     }
                 }
                 // Clear cache/transients
                 wc_delete_product_transients($clear_id);
             }
         }
     }
     // Sold Individually
     if (!empty($_POST['_sold_individually'])) {
         update_post_meta($post_id, '_sold_individually', 'yes');
     } else {
         update_post_meta($post_id, '_sold_individually', '');
     }
     // Stock Data
     if (get_option('woocommerce_manage_stock') == 'yes') {
         if ($product_type == 'grouped') {
             update_post_meta($post_id, '_manage_stock', 'no');
             update_post_meta($post_id, '_backorders', 'no');
             update_post_meta($post_id, '_stock', '');
             wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
         } elseif ($product_type == 'external') {
             update_post_meta($post_id, '_manage_stock', 'no');
             update_post_meta($post_id, '_backorders', 'no');
             update_post_meta($post_id, '_stock', '');
             wc_update_product_stock_status($post_id, 'instock');
         } elseif (!empty($_POST['_manage_stock'])) {
             update_post_meta($post_id, '_manage_stock', 'yes');
             update_post_meta($post_id, '_backorders', wc_clean($_POST['_backorders']));
             wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
             wc_update_product_stock($post_id, intval($_POST['_stock']));
         } else {
             // Don't manage stock
             update_post_meta($post_id, '_manage_stock', 'no');
             update_post_meta($post_id, '_backorders', wc_clean($_POST['_backorders']));
             update_post_meta($post_id, '_stock', '');
             wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
         }
     } else {
         wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
     }
     // Upsells
     if (isset($_POST['upsell_ids'])) {
         $upsells = array();
         $ids = $_POST['upsell_ids'];
         foreach ($ids as $id) {
             if ($id && $id > 0) {
                 $upsells[] = $id;
             }
         }
         update_post_meta($post_id, '_upsell_ids', $upsells);
     } else {
         delete_post_meta($post_id, '_upsell_ids');
     }
     // Cross sells
     if (isset($_POST['crosssell_ids'])) {
         $crosssells = array();
         $ids = $_POST['crosssell_ids'];
         foreach ($ids as $id) {
             if ($id && $id > 0) {
                 $crosssells[] = $id;
             }
         }
         update_post_meta($post_id, '_crosssell_ids', $crosssells);
     } else {
         delete_post_meta($post_id, '_crosssell_ids');
     }
     // Downloadable options
     if ($is_downloadable == 'yes') {
         $_download_limit = absint($_POST['_download_limit']);
         if (!$_download_limit) {
             $_download_limit = '';
             // 0 or blank = unlimited
         }
         $_download_expiry = absint($_POST['_download_expiry']);
         if (!$_download_expiry) {
             $_download_expiry = '';
             // 0 or blank = unlimited
         }
         // file paths will be stored in an array keyed off md5(file path)
         $files = array();
         if (isset($_POST['_wc_file_urls'])) {
             $file_names = isset($_POST['_wc_file_names']) ? array_map('wc_clean', $_POST['_wc_file_names']) : array();
             $file_urls = isset($_POST['_wc_file_urls']) ? array_map('wc_clean', $_POST['_wc_file_urls']) : array();
             $file_url_size = sizeof($file_urls);
             for ($i = 0; $i < $file_url_size; $i++) {
                 if (!empty($file_urls[$i])) {
                     $files[md5($file_urls[$i])] = array('name' => $file_names[$i], 'file' => $file_urls[$i]);
                 }
             }
         }
         // grant permission to any newly added files on any existing orders for this product prior to saving
         do_action('woocommerce_process_product_file_download_paths', $post_id, 0, $files);
         update_post_meta($post_id, '_downloadable_files', $files);
         update_post_meta($post_id, '_download_limit', $_download_limit);
         update_post_meta($post_id, '_download_expiry', $_download_expiry);
         if (isset($_POST['_download_type'])) {
             update_post_meta($post_id, '_download_type', wc_clean($_POST['_download_type']));
         }
     }
     // Product url
     if ($product_type == 'external') {
         if (isset($_POST['_product_url'])) {
             update_post_meta($post_id, '_product_url', esc_attr($_POST['_product_url']));
         }
         if (isset($_POST['_button_text'])) {
             update_post_meta($post_id, '_button_text', esc_attr($_POST['_button_text']));
         }
     }
     // Save variations
     if ($product_type == 'variable') {
         self::save_variations($post_id, $post);
     }
     // Do action for product type
     do_action('woocommerce_process_product_meta_' . $product_type, $post_id);
     // Clear cache/transients
     wc_delete_product_transients($post_id);
 }
Esempio n. 11
0
 /**
  *
  * Insert post to database
  *
  * @param $post_id
  * @param $data
  */
 function insert_product_meta($post_id, $data)
 {
     add_post_meta($post_id, 'total_sales', '0', true);
     wp_set_object_terms($post_id, 'simple', 'product_type', false);
     wc_update_product_stock_status($post_id, 'instock');
     update_post_meta($post_id, '_sale_price_dates_from', '');
     update_post_meta($post_id, '_sale_price_dates_to', '');
     update_post_meta($post_id, '_downloadable', 'no');
     update_post_meta($post_id, '_virtual', 'no');
     update_post_meta($post_id, '_sale_price', '');
     if (isset($data['_regular_price']) && $data['_regular_price'] > 0) {
         update_post_meta($post_id, '_price', $data['_regular_price']);
     }
     update_post_meta($post_id, '_tax_status', '');
     update_post_meta($post_id, '_tax_class', '');
     update_post_meta($post_id, '_purchase_note', '');
     wp_set_object_terms($post_id, '', 'product_shipping_class');
     update_post_meta($post_id, '_sku', '');
     update_post_meta($post_id, '_sold_individually', '');
     do_action('woocommerce_process_product_meta_' . 'simple', $post_id);
     wc_delete_product_transients($post_id);
 }
Esempio n. 12
0
function dokan_save_variations($post_id)
{
    global $woocommerce, $wpdb;
    $attributes = (array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true));
    if (isset($_POST['variable_sku'])) {
        $variable_post_id = $_POST['variable_post_id'];
        $variable_sku = $_POST['variable_sku'];
        $variable_regular_price = $_POST['variable_regular_price'];
        $variable_sale_price = $_POST['variable_sale_price'];
        $upload_image_id = $_POST['upload_image_id'];
        $variable_download_limit = $_POST['variable_download_limit'];
        $variable_download_expiry = $_POST['variable_download_expiry'];
        $variable_shipping_class = $_POST['variable_shipping_class'];
        $variable_tax_class = isset($_POST['variable_tax_class']) ? $_POST['variable_tax_class'] : array();
        $variable_menu_order = $_POST['variation_menu_order'];
        $variable_sale_price_dates_from = $_POST['variable_sale_price_dates_from'];
        $variable_sale_price_dates_to = $_POST['variable_sale_price_dates_to'];
        $variable_weight = isset($_POST['variable_weight']) ? $_POST['variable_weight'] : array();
        $variable_length = isset($_POST['variable_length']) ? $_POST['variable_length'] : array();
        $variable_width = isset($_POST['variable_width']) ? $_POST['variable_width'] : array();
        $variable_height = isset($_POST['variable_height']) ? $_POST['variable_height'] : array();
        $variable_stock = isset($_POST['variable_stock']) ? $_POST['variable_stock'] : array();
        $variable_manage_stock = isset($_POST['variable_manage_stock']) ? $_POST['variable_manage_stock'] : array();
        $variable_stock_status = isset($_POST['variable_stock_status']) ? $_POST['variable_stock_status'] : array();
        $variable_backorders = isset($_POST['variable_backorders']) ? $_POST['variable_backorders'] : array();
        $variable_enabled = isset($_POST['variable_enabled']) ? $_POST['variable_enabled'] : array();
        $variable_is_virtual = isset($_POST['variable_is_virtual']) ? $_POST['variable_is_virtual'] : array();
        $variable_is_downloadable = isset($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array();
        $max_loop = max(array_keys($_POST['variable_post_id']));
        for ($i = 0; $i <= $max_loop; $i++) {
            if (!isset($variable_post_id[$i])) {
                continue;
            }
            $variation_id = absint($variable_post_id[$i]);
            // Virtal/Downloadable
            $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no';
            if (isset($variable_is_virtual[$i])) {
                $is_virtual = 'yes';
            } else {
                if ($is_downloadable == 'yes') {
                    $is_virtual = 'yes';
                } else {
                    $is_virtual = 'no';
                }
            }
            // $is_virtual = isset(  ) ? 'yes' : 'no';
            // Enabled or disabled
            $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private';
            $parent_manage_stock = isset($_POST['_manage_stock']) ? 'yes' : 'no';
            $manage_stock = isset($variable_manage_stock[$i]) ? 'yes' : 'no';
            // Generate a useful post title
            $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), absint($variation_id), esc_html(get_the_title($post_id)));
            // Update or Add post
            if (!$variation_id) {
                $variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $post_id, 'post_type' => 'product_variation', 'menu_order' => $variable_menu_order[$i]);
                $variation_id = wp_insert_post($variation);
                do_action('woocommerce_create_product_variation', $variation_id);
            } else {
                $wpdb->update($wpdb->posts, array('post_status' => $post_status, 'post_title' => $variation_post_title, 'menu_order' => $variable_menu_order[$i]), array('ID' => $variation_id));
                do_action('woocommerce_update_product_variation', $variation_id);
            }
            // Only continue if we have a variation ID
            if (!$variation_id) {
                continue;
            }
            // Update post meta
            update_post_meta($variation_id, '_sku', wc_clean($variable_sku[$i]));
            //update_post_meta( $variation_id, '_stock', wc_clean( $variable_stock[ $i ] ) );
            update_post_meta($variation_id, '_thumbnail_id', absint($upload_image_id[$i]));
            update_post_meta($variation_id, '_virtual', wc_clean($is_virtual));
            update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable));
            update_post_meta($variation_id, '_manage_stock', $manage_stock);
            // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level
            if (!empty($variable_stock_status[$i])) {
                wc_update_product_stock_status($variation_id, $variable_stock_status[$i]);
            }
            if ('yes' === $manage_stock) {
                update_post_meta($variation_id, '_backorders', wc_clean($variable_backorders[$i]));
                wc_update_product_stock($variation_id, wc_stock_amount($variable_stock[$i]));
            } else {
                delete_post_meta($variation_id, '_backorders');
                delete_post_meta($variation_id, '_stock');
            }
            if (isset($variable_weight[$i])) {
                update_post_meta($variation_id, '_weight', $variable_weight[$i] === '' ? '' : wc_format_decimal($variable_weight[$i]));
            }
            if (isset($variable_length[$i])) {
                update_post_meta($variation_id, '_length', $variable_length[$i] === '' ? '' : wc_format_decimal($variable_length[$i]));
            }
            if (isset($variable_width[$i])) {
                update_post_meta($variation_id, '_width', $variable_width[$i] === '' ? '' : wc_format_decimal($variable_width[$i]));
            }
            if (isset($variable_height[$i])) {
                update_post_meta($variation_id, '_height', $variable_height[$i] === '' ? '' : wc_format_decimal($variable_height[$i]));
            }
            // Price handling
            $regular_price = wc_format_decimal($variable_regular_price[$i]);
            $sale_price = $variable_sale_price[$i] === '' ? '' : wc_format_decimal($variable_sale_price[$i]);
            $date_from = wc_clean($variable_sale_price_dates_from[$i]);
            $date_to = wc_clean($variable_sale_price_dates_to[$i]);
            update_post_meta($variation_id, '_regular_price', $regular_price);
            update_post_meta($variation_id, '_sale_price', $sale_price);
            // Save Dates
            if ($date_from) {
                update_post_meta($variation_id, '_sale_price_dates_from', strtotime($date_from));
            } else {
                update_post_meta($variation_id, '_sale_price_dates_from', '');
            }
            if ($date_to) {
                update_post_meta($variation_id, '_sale_price_dates_to', strtotime($date_to));
            } else {
                update_post_meta($variation_id, '_sale_price_dates_to', '');
            }
            if ($date_to && !$date_from) {
                update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
            }
            // Update price if on sale
            if ($sale_price != '' && $date_to == '' && $date_from == '') {
                update_post_meta($variation_id, '_price', $sale_price);
            } else {
                update_post_meta($variation_id, '_price', $regular_price);
            }
            if ($sale_price != '' && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
                update_post_meta($variation_id, '_price', $sale_price);
            }
            if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
                update_post_meta($variation_id, '_price', $regular_price);
                update_post_meta($variation_id, '_sale_price_dates_from', '');
                update_post_meta($variation_id, '_sale_price_dates_to', '');
            }
            if (isset($variable_tax_class[$i]) && $variable_tax_class[$i] !== 'parent') {
                update_post_meta($variation_id, '_tax_class', wc_clean($variable_tax_class[$i]));
            } else {
                delete_post_meta($variation_id, '_tax_class');
            }
            if ($is_downloadable == 'yes') {
                update_post_meta($variation_id, '_download_limit', wc_clean($variable_download_limit[$i]));
                update_post_meta($variation_id, '_download_expiry', wc_clean($variable_download_expiry[$i]));
                $files = array();
                $file_names = isset($_POST['_wc_variation_file_names'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_names'][$variation_id]) : array();
                $file_urls = isset($_POST['_wc_variation_file_urls'][$variation_id]) ? array_map('esc_url_raw', array_map('trim', $_POST['_wc_variation_file_urls'][$variation_id])) : array();
                $file_url_size = sizeof($file_urls);
                for ($ii = 0; $ii < $file_url_size; $ii++) {
                    if (!empty($file_urls[$ii])) {
                        $files[md5($file_urls[$ii])] = array('name' => $file_names[$ii], 'file' => $file_urls[$ii]);
                    }
                }
                // grant permission to any newly added files on any existing orders for this product prior to saving
                do_action('woocommerce_process_product_file_download_paths', $post_id, $variation_id, $files);
                update_post_meta($variation_id, '_downloadable_files', $files);
            } else {
                update_post_meta($variation_id, '_download_limit', '');
                update_post_meta($variation_id, '_download_expiry', '');
                update_post_meta($variation_id, '_downloadable_files', '');
            }
            // Save shipping class
            $variable_shipping_class[$i] = !empty($variable_shipping_class[$i]) ? (int) $variable_shipping_class[$i] : '';
            wp_set_object_terms($variation_id, $variable_shipping_class[$i], 'product_shipping_class');
            // Update taxonomies - don't use wc_clean as it destroys sanitized characters
            $updated_attribute_keys = array();
            foreach ($attributes as $attribute) {
                if ($attribute['is_variation']) {
                    $attribute_key = 'attribute_' . sanitize_title($attribute['name']);
                    $value = isset($_POST[$attribute_key][$i]) ? sanitize_title(stripslashes($_POST[$attribute_key][$i])) : '';
                    $updated_attribute_keys[] = $attribute_key;
                    update_post_meta($variation_id, $attribute_key, $value);
                }
            }
            // Remove old taxonomies attributes so data is kept up to date - first get attribute key names
            $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id));
            foreach ($delete_attribute_keys as $key) {
                delete_post_meta($variation_id, $key);
            }
            do_action('woocommerce_save_product_variation', $variation_id, $i);
        }
    }
    // Update parent if variable so price sorting works and stays in sync with the cheapest child
    WC_Product_Variable::sync($post_id);
    // Update default attribute options setting
    $default_attributes = array();
    foreach ($attributes as $attribute) {
        if ($attribute['is_variation']) {
            // Don't use wc_clean as it destroys sanitized characters
            if (isset($_POST['default_attribute_' . sanitize_title($attribute['name'])])) {
                $value = sanitize_title(trim(stripslashes($_POST['default_attribute_' . sanitize_title($attribute['name'])])));
            } else {
                $value = '';
            }
            if ($value) {
                $default_attributes[sanitize_title($attribute['name'])] = $value;
            }
        }
    }
    update_post_meta($post_id, '_default_attributes', $default_attributes);
}
 /**
  * Bulk edit.
  *
  * @param integer $post_id
  * @param WC_Product $product
  */
 public function bulk_edit_save($post_id, $product)
 {
     $old_regular_price = $product->get_regular_price();
     $old_sale_price = $product->get_sale_price();
     // Save fields
     if (!empty($_REQUEST['change_weight']) && isset($_REQUEST['_weight'])) {
         $product->set_weight(wc_clean(stripslashes($_REQUEST['_weight'])));
     }
     if (!empty($_REQUEST['change_dimensions'])) {
         if (isset($_REQUEST['_length'])) {
             $product->set_length(wc_clean(stripslashes($_REQUEST['_length'])));
         }
         if (isset($_REQUEST['_width'])) {
             $product->set_width(wc_clean(stripslashes($_REQUEST['_width'])));
         }
         if (isset($_REQUEST['_height'])) {
             $product->set_height(wc_clean(stripslashes($_REQUEST['_height'])));
         }
     }
     if (!empty($_REQUEST['_tax_status'])) {
         $product->set_tax_status(wc_clean($_REQUEST['_tax_status']));
     }
     if (!empty($_REQUEST['_tax_class'])) {
         $tax_class = wc_clean($_REQUEST['_tax_class']);
         if ('standard' == $tax_class) {
             $tax_class = '';
         }
         $product->set_tax_class($tax_class);
     }
     if (!empty($_REQUEST['_shipping_class'])) {
         $shipping_class = '_no_shipping_class' == $_REQUEST['_shipping_class'] ? '' : wc_clean($_REQUEST['_shipping_class']);
         $shipping_class_id = $data_store->get_shipping_class_id_by_slug($shipping_class);
         if ($shipping_class_id) {
             $product->set_shipping_class_id($shipping_class_id);
         }
     }
     if (!empty($_REQUEST['_visibility'])) {
         $product->set_catalog_visibility(wc_clean($_REQUEST['_visibility']));
     }
     if (!empty($_REQUEST['_featured'])) {
         $product->set_featured(stripslashes($_REQUEST['_featured']));
     }
     // Sold Individually
     if (!empty($_REQUEST['_sold_individually'])) {
         if ('yes' === $_REQUEST['_sold_individually']) {
             $product->set_sold_individually('yes');
         } else {
             $product->set_sold_individually('');
         }
     }
     // Handle price - remove dates and set to lowest
     $change_price_product_types = apply_filters('woocommerce_bulk_edit_save_price_product_types', array('simple', 'external'));
     $can_product_type_change_price = false;
     foreach ($change_price_product_types as $product_type) {
         if ($product->is_type($product_type)) {
             $can_product_type_change_price = true;
             break;
         }
     }
     if ($can_product_type_change_price) {
         $price_changed = false;
         if (!empty($_REQUEST['change_regular_price'])) {
             $change_regular_price = absint($_REQUEST['change_regular_price']);
             $regular_price = esc_attr(stripslashes($_REQUEST['_regular_price']));
             switch ($change_regular_price) {
                 case 1:
                     $new_price = $regular_price;
                     break;
                 case 2:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = $old_regular_price + round($old_regular_price * $percent, wc_get_price_decimals());
                     } else {
                         $new_price = $old_regular_price + $regular_price;
                     }
                     break;
                 case 3:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = max(0, $old_regular_price - round($old_regular_price * $percent, wc_get_price_decimals()));
                     } else {
                         $new_price = max(0, $old_regular_price - $regular_price);
                     }
                     break;
                 default:
                     break;
             }
             if (isset($new_price) && $new_price != $old_regular_price) {
                 $price_changed = true;
                 $new_price = round($new_price, wc_get_price_decimals());
                 $product->set_regular_price($new_price);
             }
         }
         if (!empty($_REQUEST['change_sale_price'])) {
             $change_sale_price = absint($_REQUEST['change_sale_price']);
             $sale_price = esc_attr(stripslashes($_REQUEST['_sale_price']));
             switch ($change_sale_price) {
                 case 1:
                     $new_price = $sale_price;
                     break;
                 case 2:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = $old_sale_price + $old_sale_price * $percent;
                     } else {
                         $new_price = $old_sale_price + $sale_price;
                     }
                     break;
                 case 3:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = max(0, $old_sale_price - $old_sale_price * $percent);
                     } else {
                         $new_price = max(0, $old_sale_price - $sale_price);
                     }
                     break;
                 case 4:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = max(0, $product->regular_price - $product->regular_price * $percent);
                     } else {
                         $new_price = max(0, $product->regular_price - $sale_price);
                     }
                     break;
                 default:
                     break;
             }
             if (isset($new_price) && $new_price != $old_sale_price) {
                 $price_changed = true;
                 $new_price = !empty($new_price) || '0' === $new_price ? round($new_price, wc_get_price_decimals()) : '';
                 $product->set_sale_price($new_price);
             }
         }
         if ($price_changed) {
             $product->set_date_on_sale_to('');
             $product->set_date_on_sale_from('');
             if ($product->get_regular_price() < $product->get_sale_price()) {
                 $product->set_sale_price('');
             }
         }
     }
     // Handle Stock Data
     $was_managing_stock = $product->get_manage_stock() ? 'yes' : 'no';
     $stock_status = $product->get_stock_status();
     $backorders = $product->get_backorders();
     $backorders = !empty($_REQUEST['_backorders']) ? wc_clean($_REQUEST['_backorders']) : $backorders;
     $stock_status = !empty($_REQUEST['_stock_status']) ? wc_clean($_REQUEST['_stock_status']) : $stock_status;
     if (!empty($_REQUEST['_manage_stock'])) {
         $manage_stock = 'yes' === wc_clean($_REQUEST['_manage_stock']) && 'grouped' !== $product->product_type ? 'yes' : 'no';
     } else {
         $manage_stock = $was_managing_stock;
     }
     $stock_amount = 'yes' === $manage_stock && isset($_REQUEST['_change_stock']) ? wc_stock_amount($_REQUEST['_change_stock']) : '';
     if ('yes' === get_option('woocommerce_manage_stock')) {
         // Apply product type constraints to stock status
         if ($product->is_type('external')) {
             // External always in stock
             $stock_status = 'instock';
         } elseif ($product->is_type('variable')) {
             // Stock status is always determined by children
             foreach ($product->get_children() as $child_id) {
                 $child = wc_get_product($child_id);
                 if (!$product->get_manage_stock()) {
                     $child->set_stock_status($stock_status);
                     $child->save();
                 }
             }
             $product = WC_Product_Variable::sync($product, false);
         }
         $product->set_manage_stock($manage_stock);
         $product->set_backorders($backorders);
         $product->save();
         if (!$product->is_type('variable')) {
             wc_update_product_stock_status($post_id, $stock_status);
         }
         wc_update_product_stock($post_id, $stock_amount);
     } else {
         $product->save();
         wc_update_product_stock_status($post_id, $stock_status);
     }
     do_action('woocommerce_product_bulk_edit_save', $product);
 }
 public function mp_save_variation($id, $data)
 {
     global $wpdb;
     /*================= my method*/
     $menu_order = 0;
     $attributes = (array) maybe_unserialize(get_post_meta($id, '_product_attributes', true));
     /*
      		echo '<pre>';
      		print_r($attributes);
      		echo '</pre>';*/
     // $data=array_reverse($data);
     $cinv = 0;
     foreach ($data as $variation_id) {
         /*start of loop*/
         $variation_id = isset($variation_id) ? absint($variation_id) : 0;
         /*if($cinv==0 && isset($_POST['new_added_variation']) && $_POST['new_added_variation']>=1){
         			$post_title='Variation #'.$id.' of Product';
         			$product_data=array(
         		   'post_author'=>get_current_user_id(),
         		   'post_content'=>'',
         		   'post_title'=>$post_title,
         		   'post_status'=>'publish',
         		   'post_type'=>'product_variation',
         		   'post_parent'=>$id,
         		   'menu_order'=>''
         		   );
         		$var_id = wp_insert_post($product_data);
         		if($var_id!=''){
         			wp_delete_post($var_id);
         		}
         		}
         		$cinv++;*/
         // SKU
         if (isset($_POST['wkmp_variable_sku'][$variation_id])) {
             $sku = get_post_meta($variation_id, '_sku', true);
             $new_sku = wc_clean($_POST['wkmp_variable_sku'][$variation_id]);
             $is_sku_unique = wc_product_has_unique_sku($variation_id, $new_sku);
             if ('' == $new_sku) {
                 update_post_meta($variation_id, '_sku', '');
             } elseif ($new_sku != $sku && $is_sku_unique) {
                 if (!empty($new_sku)) {
                     update_post_meta($variation_id, '_sku', $new_sku);
                 } else {
                     update_post_meta($variation_id, '_sku', '');
                 }
             }
         }
         // Thumbnail
         if (isset($_POST['upload_var_img'][$variation_id])) {
             $attachment_id = $_POST['upload_var_img'][$variation_id];
             if ($attachment_id) {
                 update_post_meta($variation_id, '_thumbnail_id', $attachment_id);
             } else {
                 // delete_post_meta( $variation_id, '_thumbnail_id' );
                 update_post_meta($variation_id, '_thumbnail_id', 0);
             }
         }
         // Virtual variation
         if (isset($_POST['wkmp_variable_is_virtual'][$variation_id])) {
             $is_virtual = $_POST['wkmp_variable_is_virtual'][$variation_id] == 'yes' ? 'yes' : 'no';
             update_post_meta($variation_id, '_virtual', $is_virtual);
         } else {
             update_post_meta($variation_id, '_virtual', 'no');
         }
         // Downloadable variation
         if (isset($_POST['wkmp_variable_is_downloadable'][$variation_id])) {
             $is_downloadable = 'yes' == $_POST['wkmp_variable_is_downloadable'][$variation_id] ? 'yes' : 'no';
             update_post_meta($variation_id, '_downloadable', $is_downloadable);
         } else {
             update_post_meta($variation_id, '_downloadable', 'no');
             // $is_downloadable = get_post_meta( $variation_id, '_downloadable', true );
             $is_downloadable = 'no';
         }
         /*// Shipping data
         		$this->mp_save_product_shipping_data( $variation_id, $_POST );*/
         // Stock handling
         if (isset($_POST['wkmp_variable_manage_stock'][$variation_id])) {
             $managing_stock = 'yes' == $_POST['wkmp_variable_manage_stock'][$variation_id] ? 'yes' : 'no';
             update_post_meta($variation_id, '_manage_stock', $managing_stock);
         } else {
             update_post_meta($variation_id, '_manage_stock', 'no');
             // $managing_stock = get_post_meta( $variation_id, '_manage_stock', true );
             $managing_stock = 'no';
         }
         // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level
         if (isset($_POST['wkmp_variable_stock_status'][$variation_id])) {
             $stock_status = 'instock' == $_POST['wkmp_variable_stock_status'][$variation_id] ? 'instock' : 'outofstock';
             wc_update_product_stock_status($variation_id, $stock_status);
             /*update_post_meta( $variation_id, '_stock_status', $managing_stock );*/
         }
         if ('yes' === $managing_stock) {
             if (isset($_POST['wkmp_variable_backorders'][$variation_id])) {
                 if ('notify' == $_POST['wkmp_variable_backorders'][$variation_id]) {
                     $backorders = 'notify';
                 } else {
                     $backorders = 'yes' == $_POST['wkmp_variable_backorders'][$variation_id] ? 'yes' : 'no';
                 }
             } else {
                 $backorders = 'no';
             }
             update_post_meta($variation_id, '_backorders', $backorders);
             if (isset($_POST['wkmp_variable_stock'][$variation_id])) {
                 wc_update_product_stock($variation_id, wc_stock_amount($_POST['wkmp_variable_stock'][$variation_id]));
             }
         } else {
             delete_post_meta($variation_id, '_backorders');
             delete_post_meta($variation_id, '_stock');
         }
         // Regular Price
         if (isset($_POST['wkmp_variable_regular_price'][$variation_id])) {
             $regular_price = '' === $_POST['wkmp_variable_regular_price'][$variation_id] ? '' : wc_format_decimal($_POST['wkmp_variable_regular_price'][$variation_id]);
             update_post_meta($variation_id, '_regular_price', wc_format_decimal($regular_price));
         } else {
             update_post_meta($variation_id, '_regular_price', '');
             // $regular_price = get_post_meta( $variation_id, '_regular_price', true );
             $regular_price = '';
         }
         // Sale Price
         if (isset($_POST['wkmp_variable_sale_price'][$variation_id])) {
             $sale_price = '' === $_POST['wkmp_variable_sale_price'][$variation_id] ? '' : wc_format_decimal($_POST['wkmp_variable_sale_price'][$variation_id]);
             update_post_meta($variation_id, '_sale_price', $sale_price);
         } else {
             // update_post_meta( $variation_id, '_sale_price', '' );
             // $sale_price = get_post_meta( $variation_id, '_sale_price', true );
             $sale_price = '';
         }
         $date_from = isset($_POST['wkmp_variable_sale_price_dates_from'][$variation_id]) ? strtotime($_POST['wkmp_variable_sale_price_dates_from'][$variation_id]) : get_post_meta($variation_id, '_sale_price_dates_from', true);
         $date_to = isset($_POST['wkmp_variable_sale_price_dates_to'][$variation_id]) ? strtotime($_POST['wkmp_variable_sale_price_dates_to'][$variation_id]) : get_post_meta($variation_id, '_sale_price_dates_to', true);
         // Save Dates
         if ($date_from) {
             update_post_meta($variation_id, '_sale_price_dates_from', $date_from);
         } else {
             update_post_meta($variation_id, '_sale_price_dates_from', '');
         }
         if ($date_to) {
             update_post_meta($variation_id, '_sale_price_dates_to', $date_to);
         } else {
             update_post_meta($variation_id, '_sale_price_dates_to', '');
         }
         if ($date_to && !$date_from) {
             update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
         }
         // Update price if on sale
         if ('' != $sale_price && '' == $date_to && '' == $date_from) {
             update_post_meta($variation_id, '_price', wc_format_decimal($sale_price));
         } else {
             update_post_meta($variation_id, '_price', wc_format_decimal($regular_price));
         }
         if ('' != $sale_price && $date_from && $date_from < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($variation_id, '_price', wc_format_decimal($sale_price));
         }
         if ($date_to && $date_to < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($variation_id, '_price', wc_format_decimal($regular_price));
             update_post_meta($variation_id, '_sale_price_dates_from', '');
             update_post_meta($variation_id, '_sale_price_dates_to', '');
         }
         /*// Tax class
         		if ( isset( $_POST['tax_class'] ) ) {
         			if ( $_POST['tax_class'] !== 'parent' ) {
         				update_post_meta( $variation_id, '_tax_class', wc_clean( $_POST['tax_class'] ) );
         			} else {
         				/*delete_post_meta( $variation_id, '_tax_class' );*/
         /*
         				}
         			}*/
         // Downloads
         if ('yes' == $is_downloadable && isset($_POST['_mp_variation_downloads_files_url'][$variation_id])) {
             /*// Downloadable files
             		if ( isset( $variation['downloads'] ) && is_array( $variation['downloads'] ) ) {
             			$this->save_downloadable_files( $id, $variation['downloads'], $variation_id );
             		}*/
             $variation_files = $_POST['_mp_variation_downloads_files_url'][$variation_id];
             $variation_names = isset($_POST['_mp_variation_downloads_files_name'][$variation_id]) ? $_POST['_mp_variation_downloads_files_name'][$variation_id] : '';
             $var_downloadable = array();
             $var_down_name = array();
             if (isset($_POST['_mp_variation_downloads_files_url'][$variation_id]) && count($_POST['_mp_variation_downloads_files_url'][$variation_id]) > 0) {
                 $files = array();
                 /*$file_url_size = count( $variation_files );*/
                 /*foreach ($variation_files as $key => $value) {*/
                 if (!empty($variation_files)) {
                     for ($i = 0; $i < count($variation_files); $i++) {
                         $file_url = wc_clean($variation_files[$i]);
                         if ($file_url != '') {
                             $files[md5($file_url)] = array('name' => $variation_names[$i], 'file' => $file_url);
                         }
                     }
                 }
                 update_post_meta($variation_id, '_downloadable_files', $files);
             }
             // Download limit
             if (isset($_POST['wkmp_variable_download_limit'][$variation_id])) {
                 $download_limit = absint($_POST['wkmp_variable_download_limit'][$variation_id]);
                 update_post_meta($variation_id, '_download_limit', !$download_limit ? '' : $download_limit);
             }
             // Download expiry
             if (isset($_POST['wkmp_variable_download_expiry'][$variation_id])) {
                 $download_expiry = absint($_POST['wkmp_variable_download_expiry'][$variation_id]);
                 update_post_meta($variation_id, '_download_expiry', !$download_expiry ? '' : $download_expiry);
             }
         } else {
             update_post_meta($variation_id, '_download_limit', '');
             update_post_meta($variation_id, '_download_expiry', '');
             update_post_meta($variation_id, '_downloadable_files', '');
         }
         if (isset($_POST['wkmp_variable_weight'][$variation_id])) {
             update_post_meta($variation_id, '_weight', '' === $_POST['wkmp_variable_weight'][$variation_id] ? '' : wc_format_decimal($_POST['wkmp_variable_weight'][$variation_id]));
         }
         // Product dimensions
         // Height
         if (isset($_POST['wkmp_variable_height'][$variation_id])) {
             update_post_meta($variation_id, '_height', '' === $_POST['wkmp_variable_height'][$variation_id] ? '' : wc_format_decimal($_POST['wkmp_variable_height'][$variation_id]));
         }
         // Width
         if (isset($_POST['wkmp_variable_width'][$variation_id])) {
             update_post_meta($variation_id, '_width', '' === $_POST['wkmp_variable_width'][$variation_id] ? '' : wc_format_decimal($_POST['wkmp_variable_width'][$variation_id]));
         }
         // Length
         if (isset($_POST['wkmp_variable_length'][$variation_id])) {
             update_post_meta($variation_id, '_length', '' === $_POST['wkmp_variable_length'][$variation_id] ? '' : wc_format_decimal($_POST['wkmp_variable_length'][$variation_id]));
         }
         // Virtual
         if (isset($_POST['wkmp_variable_is_virtual'][$variation_id])) {
             $virtual = true === $_POST['wkmp_variable_is_virtual'][$variation_id] ? 'yes' : 'no';
             if ('yes' == $virtual) {
                 update_post_meta($id, '_weight', '');
                 update_post_meta($id, '_length', '');
                 update_post_meta($id, '_width', '');
                 update_post_meta($id, '_height', '');
             }
         }
         /*wkmp_variable_is_virtual*/
         // Shipping class
         if (isset($data['shipping_class'])) {
             wp_set_object_terms($id, wc_clean($data['shipping_class']), 'product_shipping_class');
         }
         // Update taxonomies
         if (isset($_POST['mp_attribute_name'][$variation_id])) {
             $updated_attribute_keys = array();
             $men_odr = 0;
             foreach ($_POST['mp_attribute_name'][$variation_id] as $variation_type) {
                 $attribute['option'] = strtolower($_POST['attribute_' . $variation_type][$variation_id]);
                 $attribute['slug'] = $attribute['name'] = $variation_type;
                 if (!isset($attribute['name'])) {
                     continue;
                 }
                 $taxonomy = $attribute['name'];
                 $_attribute = array();
                 if (isset($attributes[$taxonomy])) {
                     $_attribute = $attributes[$taxonomy];
                 }
                 if (isset($_attribute['is_variation']) && $_attribute['is_variation']) {
                     $attribute_key = 'attribute_' . strtolower($_attribute['name']);
                     $attribute_value = isset($attribute['option']) ? stripslashes($attribute['option']) : '';
                     update_post_meta($variation_id, $attribute_key, $attribute_value);
                     // enable/diable variation  wkmp_variable_enabled[464]
                     if (isset($_POST['wkmp_variable_enabled'][$variation_id])) {
                         $my_post = array('ID' => $variation_id, 'post_title' => 'Variation #' . $variation_id . ' of ' . get_the_title($_POST['sell_pr_id']), 'menu_order' => $menu_order, 'post_name' => 'product-' . $_POST['sell_pr_id'] . '-variation', 'post_status' => 'publish');
                     } else {
                         $my_post = array('ID' => $variation_id, 'post_title' => 'Variation #' . $variation_id . ' of ' . get_the_title($_POST['sell_pr_id']), 'menu_order' => $menu_order, 'post_name' => 'product-' . $_POST['sell_pr_id'] . '-variation', 'post_status' => 'private');
                     }
                     // Update the post into the database
                     wp_update_post($my_post);
                     $men_odr++;
                 }
             }
             // Remove old taxonomies attributes so data is kept up to date - first get attribute key names
             // $delete_attribute_keys = $wpdb->get_col( $wpdb->prepare( "SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode( "','", $updated_attribute_keys ) . "' ) AND post_id = %d;", $variation_id ) );
             // foreach ( $delete_attribute_keys as $key ) {
             // 	delete_post_meta( $variation_id, $key );
             // }
         }
         // do_action( 'woocommerce_api_save_product_variation', $variation_id, $menu_order, $variation );
         $menu_order++;
     }
     // end of loop
     // Update parent if variable so price sorting works and stays in sync with the cheapest child
     // WC_Product_Variable::sync( $id );
     // // Update default attributes options setting
     // if ( isset( $data['default_attribute'] ) ) {
     // 	$data['default_attributes'] = $data['default_attribute'];
     // }
     /*if ( isset( $data['default_attributes'] ) && is_array( $data['default_attributes'] ) ) {
     			$default_attributes = array();
     
     			foreach ( $data['default_attributes'] as $default_attr_key => $default_attr ) {
     				if ( ! isset( $default_attr['name'] ) ) {
     					continue;
     				}
     
     				$taxonomy = sanitize_title( $default_attr['name'] );
     
     				if ( isset( $default_attr['slug'] ) ) {
     					$taxonomy = $this->mp_get_attribute_taxonomy_by_slug( $default_attr['slug'] );
     				}
     
     				if ( isset( $attributes[ $taxonomy ] ) ) {
     					$_attribute = $attributes[ $taxonomy ];
     
     					if ( $_attribute['is_variation'] ) {
     						// Don't use wc_clean as it destroys sanitized characters
     						if ( isset( $default_attr['option'] ) ) {
     							$value = sanitize_title( trim( stripslashes( $default_attr['option'] ) ) );
     						} else {
     							$value = '';
     						}
     
     						if ( $value ) {
     							$default_attributes[ $taxonomy ] = $value;
     						}
     					}
     				}
     			}
     
     			update_post_meta( $id, '_default_attributes', $default_attributes );
     		}*/
     return true;
 }
 /**
  * Save meta box data
  *
  * @deprecated 2.4.0 Deprecated in favor to WC_AJAX::save_variations()
  */
 public static function save_variations($post_id, $post)
 {
     global $wpdb;
     $attributes = (array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true));
     if (isset($_POST['variable_sku'])) {
         $variable_post_id = $_POST['variable_post_id'];
         $variable_sku = $_POST['variable_sku'];
         $variable_regular_price = $_POST['variable_regular_price'];
         $variable_sale_price = $_POST['variable_sale_price'];
         $upload_image_id = $_POST['upload_image_id'];
         $variable_download_limit = $_POST['variable_download_limit'];
         $variable_download_expiry = $_POST['variable_download_expiry'];
         $variable_shipping_class = $_POST['variable_shipping_class'];
         $variable_tax_class = isset($_POST['variable_tax_class']) ? $_POST['variable_tax_class'] : array();
         $variable_menu_order = $_POST['variation_menu_order'];
         $variable_sale_price_dates_from = $_POST['variable_sale_price_dates_from'];
         $variable_sale_price_dates_to = $_POST['variable_sale_price_dates_to'];
         $variable_weight = isset($_POST['variable_weight']) ? $_POST['variable_weight'] : array();
         $variable_length = isset($_POST['variable_length']) ? $_POST['variable_length'] : array();
         $variable_width = isset($_POST['variable_width']) ? $_POST['variable_width'] : array();
         $variable_height = isset($_POST['variable_height']) ? $_POST['variable_height'] : array();
         $variable_enabled = isset($_POST['variable_enabled']) ? $_POST['variable_enabled'] : array();
         $variable_is_virtual = isset($_POST['variable_is_virtual']) ? $_POST['variable_is_virtual'] : array();
         $variable_is_downloadable = isset($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array();
         $variable_manage_stock = isset($_POST['variable_manage_stock']) ? $_POST['variable_manage_stock'] : array();
         $variable_stock = isset($_POST['variable_stock']) ? $_POST['variable_stock'] : array();
         $variable_backorders = isset($_POST['variable_backorders']) ? $_POST['variable_backorders'] : array();
         $variable_stock_status = isset($_POST['variable_stock_status']) ? $_POST['variable_stock_status'] : array();
         $variable_description = isset($_POST['variable_description']) ? $_POST['variable_description'] : array();
         $max_loop = max(array_keys($_POST['variable_post_id']));
         for ($i = 0; $i <= $max_loop; $i++) {
             if (!isset($variable_post_id[$i])) {
                 continue;
             }
             $variation_id = absint($variable_post_id[$i]);
             // Checkboxes
             $is_virtual = isset($variable_is_virtual[$i]) ? 'yes' : 'no';
             $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no';
             $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private';
             $manage_stock = isset($variable_manage_stock[$i]) ? 'yes' : 'no';
             // Generate a useful post title
             $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), absint($variation_id), esc_html(get_the_title($post_id)));
             // Update or Add post
             if (!$variation_id) {
                 $variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $post_id, 'post_type' => 'product_variation', 'menu_order' => $variable_menu_order[$i]);
                 $variation_id = wp_insert_post($variation);
                 do_action('woocommerce_create_product_variation', $variation_id);
             } else {
                 $wpdb->update($wpdb->posts, array('post_status' => $post_status, 'post_title' => $variation_post_title, 'menu_order' => $variable_menu_order[$i]), array('ID' => $variation_id));
                 do_action('woocommerce_update_product_variation', $variation_id);
             }
             // Only continue if we have a variation ID
             if (!$variation_id) {
                 continue;
             }
             // Unique SKU
             $sku = get_post_meta($variation_id, '_sku', true);
             $new_sku = wc_clean(stripslashes($variable_sku[$i]));
             if ('' == $new_sku) {
                 update_post_meta($variation_id, '_sku', '');
             } elseif ($new_sku !== $sku) {
                 if (!empty($new_sku)) {
                     $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku);
                     if (!$unique_sku) {
                         WC_Admin_Meta_Boxes::add_error(__('Variation SKU must be unique.', 'woocommerce'));
                     } else {
                         update_post_meta($variation_id, '_sku', $new_sku);
                     }
                 } else {
                     update_post_meta($variation_id, '_sku', '');
                 }
             }
             // Update post meta
             update_post_meta($variation_id, '_thumbnail_id', absint($upload_image_id[$i]));
             update_post_meta($variation_id, '_virtual', wc_clean($is_virtual));
             update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable));
             if (isset($variable_weight[$i])) {
                 update_post_meta($variation_id, '_weight', '' === $variable_weight[$i] ? '' : wc_format_decimal($variable_weight[$i]));
             }
             if (isset($variable_length[$i])) {
                 update_post_meta($variation_id, '_length', '' === $variable_length[$i] ? '' : wc_format_decimal($variable_length[$i]));
             }
             if (isset($variable_width[$i])) {
                 update_post_meta($variation_id, '_width', '' === $variable_width[$i] ? '' : wc_format_decimal($variable_width[$i]));
             }
             if (isset($variable_height[$i])) {
                 update_post_meta($variation_id, '_height', '' === $variable_height[$i] ? '' : wc_format_decimal($variable_height[$i]));
             }
             // Stock handling
             update_post_meta($variation_id, '_manage_stock', $manage_stock);
             // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level
             if (!empty($variable_stock_status[$i])) {
                 wc_update_product_stock_status($variation_id, $variable_stock_status[$i]);
             }
             if ('yes' === $manage_stock) {
                 update_post_meta($variation_id, '_backorders', wc_clean($variable_backorders[$i]));
                 wc_update_product_stock($variation_id, wc_stock_amount($variable_stock[$i]));
             } else {
                 delete_post_meta($variation_id, '_backorders');
                 delete_post_meta($variation_id, '_stock');
             }
             // Price handling
             $regular_price = wc_format_decimal($variable_regular_price[$i]);
             $sale_price = $variable_sale_price[$i] === '' ? '' : wc_format_decimal($variable_sale_price[$i]);
             $date_from = wc_clean($variable_sale_price_dates_from[$i]);
             $date_to = wc_clean($variable_sale_price_dates_to[$i]);
             update_post_meta($variation_id, '_regular_price', $regular_price);
             update_post_meta($variation_id, '_sale_price', $sale_price);
             // Save Dates
             update_post_meta($variation_id, '_sale_price_dates_from', $date_from ? strtotime($date_from) : '');
             update_post_meta($variation_id, '_sale_price_dates_to', $date_to ? strtotime($date_to) : '');
             if ($date_to && !$date_from) {
                 update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
             }
             // Update price if on sale
             if ('' !== $sale_price && '' === $date_to && '' === $date_from) {
                 update_post_meta($variation_id, '_price', $sale_price);
             } else {
                 update_post_meta($variation_id, '_price', $regular_price);
             }
             if ('' !== $sale_price && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
                 update_post_meta($variation_id, '_price', $sale_price);
             }
             if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
                 update_post_meta($variation_id, '_price', $regular_price);
                 update_post_meta($variation_id, '_sale_price_dates_from', '');
                 update_post_meta($variation_id, '_sale_price_dates_to', '');
             }
             if (isset($variable_tax_class[$i]) && $variable_tax_class[$i] !== 'parent') {
                 update_post_meta($variation_id, '_tax_class', wc_clean($variable_tax_class[$i]));
             } else {
                 delete_post_meta($variation_id, '_tax_class');
             }
             if ('yes' == $is_downloadable) {
                 update_post_meta($variation_id, '_download_limit', wc_clean($variable_download_limit[$i]));
                 update_post_meta($variation_id, '_download_expiry', wc_clean($variable_download_expiry[$i]));
                 $files = array();
                 $file_names = isset($_POST['_wc_variation_file_names'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_names'][$variation_id]) : array();
                 $file_urls = isset($_POST['_wc_variation_file_urls'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_urls'][$variation_id]) : array();
                 $file_url_size = sizeof($file_urls);
                 $allowed_file_types = get_allowed_mime_types();
                 for ($ii = 0; $ii < $file_url_size; $ii++) {
                     if (!empty($file_urls[$ii])) {
                         // Find type and file URL
                         if (0 === strpos($file_urls[$ii], 'http')) {
                             $file_is = 'absolute';
                             $file_url = esc_url_raw($file_urls[$ii]);
                         } elseif ('[' === substr($file_urls[$ii], 0, 1) && ']' === substr($file_urls[$ii], -1)) {
                             $file_is = 'shortcode';
                             $file_url = wc_clean($file_urls[$ii]);
                         } else {
                             $file_is = 'relative';
                             $file_url = wc_clean($file_urls[$ii]);
                         }
                         $file_name = wc_clean($file_names[$ii]);
                         $file_hash = md5($file_url);
                         // Validate the file extension
                         if (in_array($file_is, array('absolute', 'relative'))) {
                             $file_type = wp_check_filetype(strtok($file_url, '?'));
                             $parsed_url = parse_url($file_url, PHP_URL_PATH);
                             $extension = pathinfo($parsed_url, PATHINFO_EXTENSION);
                             if (!empty($extension) && !in_array($file_type['type'], $allowed_file_types)) {
                                 WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not have an allowed file type. Allowed types include: %s', 'woocommerce'), '<code>' . basename($file_url) . '</code>', '<code>' . implode(', ', array_keys($allowed_file_types)) . '</code>'));
                                 continue;
                             }
                         }
                         // Validate the file exists
                         if ('relative' === $file_is && !apply_filters('woocommerce_downloadable_file_exists', file_exists($file_url), $file_url)) {
                             WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not exist on the server.', 'woocommerce'), '<code>' . $file_url . '</code>'));
                             continue;
                         }
                         $files[$file_hash] = array('name' => $file_name, 'file' => $file_url);
                     }
                 }
                 // grant permission to any newly added files on any existing orders for this product prior to saving
                 do_action('woocommerce_process_product_file_download_paths', $post_id, $variation_id, $files);
                 update_post_meta($variation_id, '_downloadable_files', $files);
             } else {
                 update_post_meta($variation_id, '_download_limit', '');
                 update_post_meta($variation_id, '_download_expiry', '');
                 update_post_meta($variation_id, '_downloadable_files', '');
             }
             update_post_meta($variation_id, '_variation_description', wp_kses_post($variable_description[$i]));
             // Save shipping class
             $variable_shipping_class[$i] = !empty($variable_shipping_class[$i]) ? (int) $variable_shipping_class[$i] : '';
             wp_set_object_terms($variation_id, $variable_shipping_class[$i], 'product_shipping_class');
             // Update Attributes
             $updated_attribute_keys = array();
             foreach ($attributes as $attribute) {
                 if ($attribute['is_variation']) {
                     $attribute_key = 'attribute_' . sanitize_title($attribute['name']);
                     $updated_attribute_keys[] = $attribute_key;
                     if ($attribute['is_taxonomy']) {
                         // Don't use wc_clean as it destroys sanitized characters
                         $value = isset($_POST[$attribute_key][$i]) ? sanitize_title(stripslashes($_POST[$attribute_key][$i])) : '';
                     } else {
                         $value = isset($_POST[$attribute_key][$i]) ? wc_clean(stripslashes($_POST[$attribute_key][$i])) : '';
                     }
                     update_post_meta($variation_id, $attribute_key, $value);
                 }
             }
             // Remove old taxonomies attributes so data is kept up to date - first get attribute key names
             $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id));
             foreach ($delete_attribute_keys as $key) {
                 delete_post_meta($variation_id, $key);
             }
             do_action('woocommerce_save_product_variation', $variation_id, $i);
         }
     }
     // Update parent if variable so price sorting works and stays in sync with the cheapest child
     WC_Product_Variable::sync($post_id);
     // Update default attribute options setting
     $default_attributes = array();
     foreach ($attributes as $attribute) {
         if ($attribute['is_variation']) {
             // Don't use wc_clean as it destroys sanitized characters
             if (isset($_POST['default_attribute_' . sanitize_title($attribute['name'])])) {
                 $value = sanitize_title(trim(stripslashes($_POST['default_attribute_' . sanitize_title($attribute['name'])])));
             } else {
                 $value = '';
             }
             if ($value) {
                 $default_attributes[sanitize_title($attribute['name'])] = $value;
             }
         }
     }
     update_post_meta($post_id, '_default_attributes', $default_attributes);
 }
 /**
  * Bulk edit
  */
 public function bulk_edit_save($post_id, $product)
 {
     $old_regular_price = $product->regular_price;
     $old_sale_price = $product->sale_price;
     // Save fields
     if (!empty($_REQUEST['change_weight']) && isset($_REQUEST['_weight'])) {
         update_post_meta($post_id, '_weight', wc_clean(stripslashes($_REQUEST['_weight'])));
     }
     if (!empty($_REQUEST['change_dimensions'])) {
         if (isset($_REQUEST['_length'])) {
             update_post_meta($post_id, '_length', wc_clean(stripslashes($_REQUEST['_length'])));
         }
         if (isset($_REQUEST['_width'])) {
             update_post_meta($post_id, '_width', wc_clean(stripslashes($_REQUEST['_width'])));
         }
         if (isset($_REQUEST['_height'])) {
             update_post_meta($post_id, '_height', wc_clean(stripslashes($_REQUEST['_height'])));
         }
     }
     if (!empty($_REQUEST['_tax_status'])) {
         update_post_meta($post_id, '_tax_status', wc_clean($_REQUEST['_tax_status']));
     }
     if (!empty($_REQUEST['_tax_class'])) {
         $tax_class = wc_clean($_REQUEST['_tax_class']);
         if ($tax_class == 'standard') {
             $tax_class = '';
         }
         update_post_meta($post_id, '_tax_class', $tax_class);
     }
     if (!empty($_REQUEST['_stock_status'])) {
         wc_update_product_stock_status($post_id, wc_clean($_REQUEST['_stock_status']));
     }
     if (!empty($_REQUEST['_visibility'])) {
         update_post_meta($post_id, '_visibility', stripslashes($_REQUEST['_visibility']));
     }
     if (!empty($_REQUEST['_featured'])) {
         update_post_meta($post_id, '_featured', stripslashes($_REQUEST['_featured']));
     }
     // Handle price - remove dates and set to lowest
     if ($product->is_type('simple') || $product->is_type('external')) {
         $price_changed = false;
         if (!empty($_REQUEST['change_regular_price'])) {
             $change_regular_price = absint($_REQUEST['change_regular_price']);
             $regular_price = esc_attr(stripslashes($_REQUEST['_regular_price']));
             switch ($change_regular_price) {
                 case 1:
                     $new_price = $regular_price;
                     break;
                 case 2:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = $old_regular_price + round($old_regular_price * $percent, absint(get_option('woocommerce_price_num_decimals')));
                     } else {
                         $new_price = $old_regular_price + $regular_price;
                     }
                     break;
                 case 3:
                     if (strstr($regular_price, '%')) {
                         $percent = str_replace('%', '', $regular_price) / 100;
                         $new_price = $old_regular_price - round($old_regular_price * $percent, absint(get_option('woocommerce_price_num_decimals')));
                     } else {
                         $new_price = $old_regular_price - $regular_price;
                     }
                     break;
             }
             if (isset($new_price) && $new_price != $old_regular_price) {
                 $price_changed = true;
                 $new_price = round($new_price, absint(get_option('woocommerce_price_num_decimals')));
                 update_post_meta($post_id, '_regular_price', $new_price);
                 $product->regular_price = $new_price;
             }
         }
         if (!empty($_REQUEST['change_sale_price'])) {
             $change_sale_price = absint($_REQUEST['change_sale_price']);
             $sale_price = esc_attr(stripslashes($_REQUEST['_sale_price']));
             switch ($change_sale_price) {
                 case 1:
                     $new_price = $sale_price;
                     break;
                 case 2:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = $old_sale_price + $old_sale_price * $percent;
                     } else {
                         $new_price = $old_sale_price + $sale_price;
                     }
                     break;
                 case 3:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = $old_sale_price - $old_sale_price * $percent;
                     } else {
                         $new_price = $old_sale_price - $sale_price;
                     }
                     break;
                 case 4:
                     if (strstr($sale_price, '%')) {
                         $percent = str_replace('%', '', $sale_price) / 100;
                         $new_price = $product->regular_price - $product->regular_price * $percent;
                     } else {
                         $new_price = $product->regular_price - $sale_price;
                     }
                     break;
             }
             if (isset($new_price) && $new_price != $old_sale_price) {
                 $price_changed = true;
                 $new_price = round($new_price, absint(get_option('woocommerce_price_num_decimals')));
                 update_post_meta($post_id, '_sale_price', $new_price);
                 $product->sale_price = $new_price;
             }
         }
         if ($price_changed) {
             update_post_meta($post_id, '_sale_price_dates_from', '');
             update_post_meta($post_id, '_sale_price_dates_to', '');
             if ($product->regular_price < $product->sale_price) {
                 $product->sale_price = '';
                 update_post_meta($post_id, '_sale_price', '');
             }
             if ($product->sale_price) {
                 update_post_meta($post_id, '_price', $product->sale_price);
             } else {
                 update_post_meta($post_id, '_price', $product->regular_price);
             }
         }
     }
     // Handle stock
     if (!$product->is_type('grouped')) {
         if (!empty($_REQUEST['change_stock'])) {
             update_post_meta($post_id, '_manage_stock', 'yes');
             wc_update_product_stock($post_id, intval($_REQUEST['_stock']));
         }
         if (!empty($_REQUEST['_manage_stock'])) {
             if ($_REQUEST['_manage_stock'] == 'yes') {
                 update_post_meta($post_id, '_manage_stock', 'yes');
             } else {
                 update_post_meta($post_id, '_manage_stock', 'no');
                 wc_update_product_stock($post_id, 0);
             }
         }
         if (!empty($_REQUEST['_backorders'])) {
             update_post_meta($post_id, '_backorders', wc_clean($_REQUEST['_backorders']));
         }
     }
     do_action('woocommerce_product_bulk_edit_save', $product);
 }
 /**
  * Save variations
  *
  * @since 2.2
  * @param int $id
  * @param array $data
  * @return bool
  */
 protected function save_variations($id, $data)
 {
     global $wpdb;
     $variations = $data['variations'];
     $attributes = (array) maybe_unserialize(get_post_meta($id, '_product_attributes', true));
     foreach ($variations as $menu_order => $variation) {
         $variation_id = isset($variation['id']) ? absint($variation['id']) : 0;
         // Generate a useful post title
         $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), $variation_id, esc_html(get_the_title($id)));
         // Update or Add post
         if (!$variation_id) {
             $post_status = isset($variation['visible']) && false === $variation['visible'] ? 'private' : 'publish';
             $new_variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $id, 'post_type' => 'product_variation', 'menu_order' => $menu_order);
             $variation_id = wp_insert_post($new_variation);
             do_action('woocommerce_create_product_variation', $variation_id);
         } else {
             $update_variation = array('post_title' => $variation_post_title, 'menu_order' => $menu_order);
             if (isset($variation['visible'])) {
                 $post_status = false === $variation['visible'] ? 'private' : 'publish';
                 $update_variation['post_status'] = $post_status;
             }
             $wpdb->update($wpdb->posts, $update_variation, array('ID' => $variation_id));
             do_action('woocommerce_update_product_variation', $variation_id);
         }
         // Stop with we don't have a variation ID
         if (is_wp_error($variation_id)) {
             throw new WC_API_Exception('woocommerce_api_cannot_save_product_variation', $variation_id->get_error_message(), 400);
         }
         // SKU
         if (isset($variation['sku'])) {
             $sku = get_post_meta($variation_id, '_sku', true);
             $new_sku = wc_clean($variation['sku']);
             if ('' == $new_sku) {
                 update_post_meta($variation_id, '_sku', '');
             } elseif ($new_sku !== $sku) {
                 if (!empty($new_sku)) {
                     $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku);
                     if (!$unique_sku) {
                         throw new WC_API_Exception('woocommerce_api_product_sku_already_exists', __('The SKU already exists on another product', 'woocommerce'), 400);
                     } else {
                         update_post_meta($variation_id, '_sku', $new_sku);
                     }
                 } else {
                     update_post_meta($variation_id, '_sku', '');
                 }
             }
         }
         // Thumbnail
         if (isset($variation['image']) && is_array($variation['image'])) {
             $image = current($variation['image']);
             if ($image && is_array($image)) {
                 if (isset($image['position']) && isset($image['src']) && $image['position'] == 0) {
                     $upload = $this->upload_product_image(wc_clean($image['src']));
                     if (is_wp_error($upload)) {
                         throw new WC_API_Exception('woocommerce_api_cannot_upload_product_image', $upload->get_error_message(), 400);
                     }
                     $attachment_id = $this->set_product_image_as_attachment($upload, $id);
                     update_post_meta($variation_id, '_thumbnail_id', $attachment_id);
                 }
             } else {
                 delete_post_meta($variation_id, '_thumbnail_id');
             }
         }
         // Virtual variation
         if (isset($variation['virtual'])) {
             $is_virtual = true === $variation['virtual'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_virtual', $is_virtual);
         }
         // Downloadable variation
         if (isset($variation['downloadable'])) {
             $is_downloadable = true === $variation['downloadable'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_downloadable', $is_downloadable);
         } else {
             $is_downloadable = get_post_meta($variation_id, '_downloadable', true);
         }
         // Shipping data
         $this->save_product_shipping_data($variation_id, $variation);
         // Stock handling
         if (isset($variation['managing_stock'])) {
             $managing_stock = true === $variation['managing_stock'] ? 'yes' : 'no';
             update_post_meta($variation_id, '_manage_stock', $managing_stock);
         } else {
             $managing_stock = get_post_meta($variation_id, '_manage_stock', true);
         }
         // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level
         if (isset($variation['in_stock'])) {
             $stock_status = true === $variation['in_stock'] ? 'instock' : 'outofstock';
             wc_update_product_stock_status($variation_id, $stock_status);
         }
         if ('yes' === $managing_stock) {
             if (isset($variation['backorders'])) {
                 if ('notify' == $variation['backorders']) {
                     $backorders = 'notify';
                 } else {
                     $backorders = true === $variation['backorders'] ? 'yes' : 'no';
                 }
             } else {
                 $backorders = 'no';
             }
             update_post_meta($variation_id, '_backorders', $backorders);
             if (isset($variation['stock_quantity'])) {
                 wc_update_product_stock($variation_id, wc_stock_amount($variation['stock_quantity']));
             } else {
                 if (isset($data['inventory_delta'])) {
                     $stock_quantity = wc_stock_amount(get_post_meta($variation_id, '_stock', true));
                     $stock_quantity += wc_stock_amount($data['inventory_delta']);
                     wc_update_product_stock($variation_id, wc_stock_amount($stock_quantity));
                 }
             }
         } else {
             delete_post_meta($variation_id, '_backorders');
             delete_post_meta($variation_id, '_stock');
         }
         // Regular Price
         if (isset($variation['regular_price'])) {
             $regular_price = '' === $variation['regular_price'] ? '' : wc_format_decimal($variation['regular_price']);
             update_post_meta($variation_id, '_regular_price', $regular_price);
         } else {
             $regular_price = get_post_meta($variation_id, '_regular_price', true);
         }
         // Sale Price
         if (isset($variation['sale_price'])) {
             $sale_price = '' === $variation['sale_price'] ? '' : wc_format_decimal($variation['sale_price']);
             update_post_meta($variation_id, '_sale_price', $sale_price);
         } else {
             $sale_price = get_post_meta($variation_id, '_sale_price', true);
         }
         $date_from = isset($variation['sale_price_dates_from']) ? strtotime($variation['sale_price_dates_from']) : get_post_meta($variation_id, '_sale_price_dates_from', true);
         $date_to = isset($variation['sale_price_dates_to']) ? strtotime($variation['sale_price_dates_to']) : get_post_meta($variation_id, '_sale_price_dates_to', true);
         // Save Dates
         if ($date_from) {
             update_post_meta($variation_id, '_sale_price_dates_from', $date_from);
         } else {
             update_post_meta($variation_id, '_sale_price_dates_from', '');
         }
         if ($date_to) {
             update_post_meta($variation_id, '_sale_price_dates_to', $date_to);
         } else {
             update_post_meta($variation_id, '_sale_price_dates_to', '');
         }
         if ($date_to && !$date_from) {
             update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp')));
         }
         // Update price if on sale
         if ('' != $sale_price && '' == $date_to && '' == $date_from) {
             update_post_meta($variation_id, '_price', $sale_price);
         } else {
             update_post_meta($variation_id, '_price', $regular_price);
         }
         if ('' != $sale_price && $date_from && $date_from < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($variation_id, '_price', $sale_price);
         }
         if ($date_to && $date_to < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($variation_id, '_price', $regular_price);
             update_post_meta($variation_id, '_sale_price_dates_from', '');
             update_post_meta($variation_id, '_sale_price_dates_to', '');
         }
         // Tax class
         if (isset($variation['tax_class'])) {
             if ($variation['tax_class'] !== 'parent') {
                 update_post_meta($variation_id, '_tax_class', wc_clean($variation['tax_class']));
             } else {
                 delete_post_meta($variation_id, '_tax_class');
             }
         }
         // Downloads
         if ('yes' == $is_downloadable) {
             // Downloadable files
             if (isset($variation['downloads']) && is_array($variation['downloads'])) {
                 $this->save_downloadable_files($id, $variation['downloads'], $variation_id);
             }
             // Download limit
             if (isset($variation['download_limit'])) {
                 $download_limit = absint($variation['download_limit']);
                 update_post_meta($variation_id, '_download_limit', !$download_limit ? '' : $download_limit);
             }
             // Download expiry
             if (isset($variation['download_expiry'])) {
                 $download_expiry = absint($variation['download_expiry']);
                 update_post_meta($variation_id, '_download_expiry', !$download_expiry ? '' : $download_expiry);
             }
         } else {
             update_post_meta($variation_id, '_download_limit', '');
             update_post_meta($variation_id, '_download_expiry', '');
             update_post_meta($variation_id, '_downloadable_files', '');
         }
         // Update taxonomies
         if (isset($variation['attributes'])) {
             $updated_attribute_keys = array();
             foreach ($variation['attributes'] as $attribute_key => $attribute) {
                 if (!isset($attribute['name'])) {
                     continue;
                 }
                 $_attribute = array();
                 if (isset($attribute['slug'])) {
                     $taxonomy = $this->get_attribute_taxonomy_by_slug($attribute['slug']);
                 }
                 if (!$taxonomy) {
                     $taxonomy = sanitize_title($attribute['name']);
                 }
                 if (isset($attributes[$taxonomy])) {
                     $_attribute = $attributes[$taxonomy];
                 }
                 if (isset($_attribute['is_variation']) && $_attribute['is_variation']) {
                     $_attribute_key = 'attribute_' . sanitize_title($_attribute['name']);
                     $updated_attribute_keys[] = $_attribute_key;
                     if (isset($_attribute['is_taxonomy']) && $_attribute['is_taxonomy']) {
                         // Don't use wc_clean as it destroys sanitized characters
                         $_attribute_value = isset($attribute['option']) ? sanitize_title(stripslashes($attribute['option'])) : '';
                     } else {
                         $_attribute_value = isset($attribute['option']) ? wc_clean(stripslashes($attribute['option'])) : '';
                     }
                     update_post_meta($variation_id, $_attribute_key, $_attribute_value);
                 }
             }
             // Remove old taxonomies attributes so data is kept up to date - first get attribute key names
             $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id));
             foreach ($delete_attribute_keys as $key) {
                 delete_post_meta($variation_id, $key);
             }
         }
         do_action('woocommerce_api_save_product_variation', $variation_id, $menu_order, $variation);
     }
     // Update parent if variable so price sorting works and stays in sync with the cheapest child
     WC_Product_Variable::sync($id);
     // Update default attributes options setting
     if (isset($data['default_attribute'])) {
         $data['default_attributes'] = $data['default_attribute'];
     }
     if (isset($data['default_attributes']) && is_array($data['default_attributes'])) {
         $default_attributes = array();
         foreach ($data['default_attributes'] as $default_attr_key => $default_attr) {
             if (!isset($default_attr['name'])) {
                 continue;
             }
             $taxonomy = sanitize_title($default_attr['name']);
             if (isset($default_attr['slug'])) {
                 $taxonomy = $this->get_attribute_taxonomy_by_slug($default_attr['slug']);
             }
             if (isset($attributes[$taxonomy])) {
                 $_attribute = $attributes[$taxonomy];
                 if ($_attribute['is_variation']) {
                     $value = '';
                     if (isset($default_attr['option'])) {
                         if ($_attribute['is_taxonomy']) {
                             // Don't use wc_clean as it destroys sanitized characters
                             $value = sanitize_title(trim(stripslashes($default_attr['option'])));
                         } else {
                             $value = wc_clean(trim(stripslashes($default_attr['option'])));
                         }
                     }
                     if ($value) {
                         $default_attributes[$taxonomy] = $value;
                     }
                 }
             }
         }
         update_post_meta($id, '_default_attributes', $default_attributes);
     }
     return true;
 }
Esempio n. 18
0
 public static function saveProducts(&$data, &$children, &$currentpos, &$batchnumber)
 {
     global $wpdb;
     $posts = $wpdb->posts;
     $meta = $wpdb->postmeta;
     $temptable = $wpdb->prefix . "wpmelon_advbedit_temp";
     $term = $wpdb->term_relationships;
     $handledchildren = array();
     $sel_fields = get_option('w3exabe_custom');
     $handledattrs = array();
     $attributes = array();
     $attrmapslugtoname = array();
     $parentattrs_cache = array();
     $update_parent_attr = array();
     $update_vars_price = array();
     self::GetAttributes($attributes, $attrmapslugtoname);
     $tax_classes = array();
     self::GetTaxClasses($tax_classes);
     $retarray = array();
     $counter = 0;
     $processcounter = 0;
     self::WriteDebugInfo("clear", "");
     $rowstoskip = -1;
     if ($currentpos !== -1) {
         $rowstoskip = $currentpos * $batchnumber;
         if ($rowstoskip >= count($data)) {
             $rowstoskip = -1;
         }
         $currentpos++;
     }
     foreach ($data as $arrrow) {
         if (!is_array($arrrow)) {
             continue;
         }
         $counter++;
         $oldpost = null;
         if ($rowstoskip !== -1) {
             if ($counter <= $rowstoskip) {
                 continue;
             }
             if ($processcounter < $batchnumber) {
                 $processcounter++;
             } else {
                 continue;
             }
         }
         //			self::WriteDebugInfo("loop number ".__LINE__,$curr_settings);
         self::WriteDebugInfo("loop number " . $counter, "");
         $ID = 0;
         if (array_key_exists('ID', $arrrow)) {
             $ID = (int) $arrrow['ID'];
             $parentid = 0;
             if (array_key_exists('post_parent', $arrrow)) {
                 $parentid = (int) $arrrow['post_parent'];
             }
             if (array_key_exists('_sale_price', $arrrow)) {
                 $arrrow['_sale_price'] = str_replace(",", ".", $arrrow['_sale_price']);
             }
             if (array_key_exists('_regular_price', $arrrow)) {
                 $arrrow['_regular_price'] = str_replace(",", ".", $arrrow['_regular_price']);
             }
             if ($ID < 0) {
                 continue;
             }
             if (self::$bsavepost) {
                 $oldpost = get_post($ID);
             }
             $where = "";
             $fields = "";
             foreach ($arrrow as $i => $Row) {
                 if (is_array($sel_fields) && !empty($sel_fields)) {
                     if (array_key_exists($i, $sel_fields)) {
                         if (isset($sel_fields[$i]['type'])) {
                             if ($sel_fields[$i]['type'] === 'customh') {
                                 if (taxonomy_exists($i)) {
                                     $cat_ids = explode(',', $Row);
                                     $cat_ids = array_map('intval', $cat_ids);
                                     $cat_ids = array_unique($cat_ids);
                                     wp_set_object_terms($ID, $cat_ids, $i);
                                 }
                                 continue;
                             } elseif ($sel_fields[$i]['type'] === 'custom') {
                                 if (isset($sel_fields[$i]['isnewvals']) && $sel_fields[$i]['isnewvals'] === 'true' && taxonomy_exists($i)) {
                                     $cat_ids = explode(',', $Row);
                                     $cat_ids = array_map('trim', $cat_ids);
                                     $cat_ids = array_unique($cat_ids);
                                     wp_set_object_terms($ID, $cat_ids, $i);
                                 } else {
                                     $cat_ids = explode(',', $Row);
                                     $cat_ids = array_map('trim', $cat_ids);
                                     $cat_ids = array_unique($cat_ids);
                                     $new_ids = array();
                                     foreach ($cat_ids as $value) {
                                         if (term_exists($value, $i)) {
                                             $new_ids[] = $value;
                                         }
                                     }
                                     wp_set_object_terms($ID, $new_ids, $i);
                                 }
                                 continue;
                             }
                         }
                     }
                 }
                 switch ($i) {
                     case "post_title":
                         $query = "UPDATE {$posts} SET post_title='" . $Row . "' WHERE ID={$ID}";
                         $wpdb->query($query);
                         break;
                     case "post_content":
                         $Row = str_replace("\r\n", "\n", $Row);
                         $Row = str_replace("\n", "\r\n", $Row);
                         $query = "UPDATE {$posts} SET post_content='" . $Row . "' WHERE ID={$ID}";
                         $wpdb->query($query);
                         break;
                     case "post_excerpt":
                         $Row = str_replace("\r\n", "\n", $Row);
                         $Row = str_replace("\n", "\r\n", $Row);
                         $query = "UPDATE {$posts} SET post_excerpt='" . $Row . "' WHERE ID={$ID}";
                         $wpdb->query($query);
                         break;
                     case "post_name":
                         $slug = apply_filters('sanitize_title', $Row);
                         $slug = sanitize_title_with_dashes($slug, '', 'save');
                         $slug = wp_unique_post_slug($slug, $ID, 'publish', 'product', 0);
                         $query = "UPDATE {$posts} SET post_name='{$slug}' WHERE ID={$ID}";
                         $wpdb->query($query);
                         $newvar = new stdClass();
                         $newvar->ID = (string) $ID;
                         $newvar->post_name = $slug;
                         $permalink = get_permalink($ID);
                         if (false !== $permalink) {
                             $newvar->_product_permalink = $permalink;
                         }
                         $retarray[] = $newvar;
                         break;
                     case "post_date":
                         $date = $Row;
                         $date1 = new DateTime($date);
                         $date = $date1->format('Y-m-d');
                         //							$datenow = new DateTime();
                         $date = $date . ' ' . date('H:i:s');
                         $date_gmt = get_gmt_from_date($date);
                         $query = "UPDATE {$posts} SET post_date='{$date}', post_date_gmt='{$date_gmt}' WHERE ID={$ID}";
                         $wpdb->query($query);
                         break;
                     case "menu_order":
                         $query = "UPDATE {$posts} SET menu_order='" . intval($Row) . "' WHERE ID={$ID}";
                         $wpdb->query($query);
                         break;
                     case "comment_status":
                         if ($Row == 'yes') {
                             $query = "UPDATE {$posts} SET comment_status='open' WHERE ID={$ID}";
                         } else {
                             $query = "UPDATE {$posts} SET comment_status='closed' WHERE ID={$ID}";
                         }
                         $wpdb->query($query);
                         break;
                     case "_visibility":
                         $visibility = "visible";
                         if ($Row == "Catalog/search") {
                             $visibility = "visible";
                         }
                         if ($Row == "Catalog") {
                             $visibility = "catalog";
                         }
                         if ($Row == "Search") {
                             $visibility = "search";
                         }
                         if ($Row == "Hidden") {
                             $visibility = "hidden";
                         }
                         update_post_meta($ID, '_visibility', $visibility);
                         break;
                     case "grouped_items":
                         $cat_ids = explode(',', $Row);
                         $cat_ids = array_map('intval', $cat_ids);
                         $cat_ids = array_unique($cat_ids);
                         if (count($cat_ids) > 0) {
                             $query = "UPDATE {$posts} SET post_parent='.{$cat_ids['0']}.' WHERE ID={$ID}";
                             $wpdb->query($query);
                         }
                         break;
                     case "product_cat":
                         $cat_ids = explode(',', $Row);
                         $cat_ids = array_map('intval', $cat_ids);
                         $cat_ids = array_unique($cat_ids);
                         wp_set_object_terms($ID, $cat_ids, 'product_cat');
                         //							self::WriteDebugInfo("loop number ".__LINE__,$curr_settings);
                         break;
                     case "product_tag":
                         $cat_ids = explode(',', $Row);
                         $cat_ids = array_map('trim', $cat_ids);
                         $cat_ids = array_unique($cat_ids);
                         wp_set_object_terms($ID, $cat_ids, 'product_tag');
                         break;
                     case "product_shipping_class":
                         $cat_ids = explode(',', $Row);
                         $cat_ids = array_map('intval', $cat_ids);
                         $cat_ids = array_unique($cat_ids);
                         wp_set_object_terms($ID, $cat_ids, 'product_shipping_class');
                         break;
                     case "product_type":
                         $cat_ids = explode(',', $Row);
                         $cat_ids = array_map('intval', $cat_ids);
                         $cat_ids = array_unique($cat_ids);
                         wp_set_object_terms($ID, $cat_ids, 'product_type');
                         break;
                     case "_download_expiry":
                         update_post_meta($ID, '_download_expiry', $Row);
                         break;
                     case "_download_limit":
                         update_post_meta($ID, '_download_limit', $Row);
                         break;
                     case "_download_type":
                         $down_type = "";
                         if ($Row == "Application") {
                             $down_type = "application";
                         }
                         if ($Row == "Music") {
                             $down_type = "music";
                         }
                         update_post_meta($ID, '_download_type', $down_type);
                         break;
                     case "_downloadable_files":
                         $down_files = array();
                         $files = array();
                         $down_files = explode('*****', $Row);
                         if ($down_files) {
                             for ($i = 0; $i < count($down_files); $i++) {
                                 $itemsarr = $down_files[$i];
                                 if (!isset($itemsarr) || $itemsarr === "") {
                                     continue;
                                 }
                                 $items = explode('#####', $itemsarr);
                                 $name = "";
                                 for ($j = 0; $j < count($items); $j++) {
                                     $item = $items[$j];
                                     if (!isset($item) || $item === "") {
                                         continue;
                                     }
                                     if ($j == 0) {
                                         //name
                                         $name = $item;
                                     } else {
                                         //url
                                         if ($item != "") {
                                             $files[md5($item)] = array('name' => $name, 'file' => $item);
                                         }
                                     }
                                 }
                             }
                         } else {
                             $items = explode('#####', $Row);
                             $name = "";
                             if ($items) {
                                 for ($j = 0; $j < count($items); $j++) {
                                     $item = $items[$j];
                                     if (!isset($item) || $item === "") {
                                         continue;
                                     }
                                     if ($j == 0) {
                                         //name
                                         $name = $item;
                                     } else {
                                         //url
                                         if ($item != "") {
                                             $files[md5($item)] = array('name' => $name, 'file' => $item);
                                         }
                                     }
                                 }
                             }
                         }
                         self::HandleFiles($ID, $files);
                         update_post_meta($ID, '_downloadable_files', $files);
                         break;
                     case "_upsell_ids":
                         if ($Row === "") {
                             delete_post_meta($ID, '_upsell_ids');
                         } else {
                             $sell_ids = array();
                             $sell_idsch = explode(',', $Row);
                             if ($sell_idsch) {
                                 for ($i = 0; $i < count($sell_idsch); $i++) {
                                     $itemsarr = $sell_idsch[$i];
                                     $itemsarr = trim($itemsarr);
                                     if (!isset($itemsarr) || $itemsarr === "") {
                                         continue;
                                     }
                                     if (!is_numeric($itemsarr)) {
                                         continue;
                                     }
                                     $sell_ids[] = absint($itemsarr);
                                 }
                             }
                             update_post_meta($ID, '_upsell_ids', $sell_ids);
                         }
                         break;
                     case "_crosssell_ids":
                         if ($Row === "") {
                             delete_post_meta($ID, '_crosssell_ids');
                         } else {
                             $sell_ids = array();
                             $sell_idsch = explode(',', $Row);
                             if ($sell_idsch) {
                                 for ($i = 0; $i < count($sell_idsch); $i++) {
                                     $itemsarr = $sell_idsch[$i];
                                     $itemsarr = trim($itemsarr);
                                     if (!isset($itemsarr) || $itemsarr === "") {
                                         continue;
                                     }
                                     if (!is_numeric($itemsarr)) {
                                         continue;
                                     }
                                     $sell_ids[] = absint($itemsarr);
                                 }
                             }
                             update_post_meta($ID, '_crosssell_ids', $sell_ids);
                         }
                         break;
                     case "post_status":
                         $query = "SELECT post_type FROM {$posts} WHERE ID={$ID}";
                         $ret = $wpdb->get_var($query);
                         $bcallaction = false;
                         $old_status = "";
                         $post = new stdClass();
                         if ($ret === 'product') {
                             $post = get_post($ID);
                             $old_status = $post->post_status;
                             $bcallaction = true;
                         }
                         if ($Row == 'publish' && $ret === 'product') {
                             $query = "SELECT {$posts}.post_name FROM {$posts} WHERE {$posts}.ID={$ID}";
                             $ret = $wpdb->get_var($query);
                             if (!is_wp_error($ret) && $ret == '') {
                                 $query = "SELECT post_title, post_date FROM {$posts} WHERE {$posts}.ID={$ID}";
                                 $ret = $wpdb->get_results($query);
                                 if (!is_wp_error($ret) && count($ret) == 1) {
                                     $obj = $ret[0];
                                     $slug = apply_filters('sanitize_title', $obj->post_title, $obj->post_title, 'save');
                                     $slug = sanitize_title_with_dashes($slug, '', 'save');
                                     $slug = wp_unique_post_slug($slug, $ID, 'publish', 'product', 0);
                                     $date_gmt = get_gmt_from_date($obj->post_date);
                                     $query = "UPDATE {$posts} SET post_name='{$slug}',post_status='publish',post_date_gmt='{$date_gmt}' WHERE ID={$ID}";
                                     $wpdb->query($query);
                                     $newvar = new stdClass();
                                     $newvar->ID = (string) $ID;
                                     $newvar->post_name = $slug;
                                     $permalink = get_permalink($ID);
                                     $newvar->_product_permalink = "";
                                     if (false !== $permalink) {
                                         $newvar->_product_permalink = $permalink;
                                     }
                                     $retarray[] = $newvar;
                                 }
                             } else {
                                 $query = "UPDATE {$posts} SET post_status='" . $Row . "' WHERE ID={$ID}";
                                 $wpdb->query($query);
                             }
                         } else {
                             $query = "UPDATE {$posts} SET post_status='" . $Row . "' WHERE ID={$ID}";
                             $wpdb->query($query);
                         }
                         if ($bcallaction) {
                             wp_transition_post_status($Row, $old_status, $post);
                         }
                         break;
                     case "_sale_price_dates_from":
                         $value = strtotime($Row);
                         update_post_meta($ID, $i, $value);
                         break;
                     case "_sale_price_dates_to":
                         $value = strtotime($Row);
                         update_post_meta($ID, $i, $value);
                         break;
                     case "_tax_class":
                         $class = "";
                         if (count($tax_classes) === 0) {
                             if ($Row == "Reduced Rate") {
                                 $class = "reduced-rate";
                             }
                             if ($Row == "Zero Rate") {
                                 $class = "zero-rate";
                             }
                         } else {
                             foreach ($tax_classes as $key => $value) {
                                 if ($value === $Row) {
                                     $class = $key;
                                     break;
                                 }
                             }
                         }
                         update_post_meta($ID, $i, $class);
                         break;
                     case "_tax_status":
                         $class = "taxable";
                         if ($Row == "Shipping only") {
                             $class = "shipping";
                         }
                         if ($Row == "None") {
                             $class = "none";
                         }
                         update_post_meta($ID, $i, $class);
                         break;
                     case "_sold_individually":
                         $back = "";
                         if ($Row == "no") {
                             $back = "";
                         }
                         if ($Row == "yes") {
                             $back = "yes";
                         }
                         update_post_meta($ID, $i, $back);
                         break;
                     case "_backorders":
                         $back = "no";
                         if ($Row == "Do not allow") {
                             $back = "no";
                         }
                         if ($Row == "Allow but notify") {
                             $back = "notify";
                         }
                         if ($Row == "Allow") {
                             $back = "yes";
                         }
                         update_post_meta($ID, $i, $back);
                         break;
                     case "_default_attributes":
                         $def_attrs = array();
                         $cur_attr = array();
                         $all_attrs = explode(';', $Row);
                         if (is_array($all_attrs) && count($all_attrs) > 0) {
                             for ($i = 0; $i < count($all_attrs); $i++) {
                                 $itemsarr = $all_attrs[$i];
                                 $itemsarr = trim($itemsarr);
                                 if (!isset($itemsarr) || $itemsarr === "") {
                                     continue;
                                 }
                                 $items = explode(',', $itemsarr);
                                 $name = "";
                                 if (!is_array($items)) {
                                     continue;
                                 }
                                 $cur_attr = array();
                                 for ($j = 0; $j < count($items); $j++) {
                                     $item = $items[$j];
                                     if (!isset($item) || $item === "") {
                                         continue;
                                     }
                                     if ($j == 0) {
                                         //name
                                         $name = $item;
                                     } else {
                                         //url
                                         if ($item != "") {
                                             $def_attrs[$name] = $item;
                                         }
                                     }
                                 }
                             }
                         }
                         update_post_meta($ID, '_default_attributes', $def_attrs);
                         break;
                     case "_custom_attributes":
                         $query = "SELECT post_type FROM {$posts} WHERE ID={$ID}";
                         $ret = $wpdb->get_var($query);
                         if ($ret === 'product') {
                             $attributessave = array();
                             $attributessave = explode('*****', $Row);
                             $patt = get_post_meta($ID, '_product_attributes', true);
                             $taxonomy_slug = "";
                             if (!is_array($patt)) {
                                 $patt = array();
                             }
                             $attrsaved = array();
                             if ($attributessave) {
                                 for ($i = 0; $i < count($attributessave); $i++) {
                                     $itemsarr = $attributessave[$i];
                                     $insertarr = array();
                                     if (!isset($itemsarr) || $itemsarr === "") {
                                         continue;
                                     }
                                     $items = explode('#####', $itemsarr);
                                     for ($j = 0; $j < count($items); $j++) {
                                         $item = $items[$j];
                                         if (!isset($item) || $item === "") {
                                             continue;
                                         }
                                         switch ($j) {
                                             case 0:
                                                 //name
                                                 $taxonomy_slug = sanitize_title($item);
                                                 $insertarr["name"] = $item;
                                                 break;
                                             case 1:
                                                 //value
                                                 $insertarr["value"] = $item;
                                                 break;
                                             case 2:
                                                 //is_visible
                                                 $insertarr["is_visible"] = (int) $item;
                                                 break;
                                             case 3:
                                                 //is_variation
                                                 $insertarr["is_variation"] = (int) $item;
                                                 break;
                                             default:
                                                 break;
                                         }
                                     }
                                     if (isset($patt[$taxonomy_slug])) {
                                         $patt[$taxonomy_slug]["name"] = $insertarr["name"];
                                         $patt[$taxonomy_slug]["value"] = $insertarr["value"];
                                         $patt[$taxonomy_slug]["is_visible"] = $insertarr["is_visible"];
                                         $patt[$taxonomy_slug]["is_variation"] = $insertarr["is_variation"];
                                         $patt[$taxonomy_slug]["is_taxonomy"] = 0;
                                         //											$patt[$taxonomy_slug]["position"] = count($patt);
                                     } else {
                                         $patt[$taxonomy_slug] = array();
                                         $patt[$taxonomy_slug]["name"] = $insertarr["name"];
                                         $patt[$taxonomy_slug]["value"] = $insertarr["value"];
                                         $patt[$taxonomy_slug]["is_visible"] = $insertarr["is_visible"];
                                         $patt[$taxonomy_slug]["is_variation"] = $insertarr["is_variation"];
                                         $patt[$taxonomy_slug]["is_taxonomy"] = 0;
                                         $patt[$taxonomy_slug]["position"] = count($patt);
                                     }
                                     $attrsaved[$taxonomy_slug] = 1;
                                 }
                             } else {
                                 $items = explode('#####', $itemsarr);
                                 for ($j = 0; $j < count($items); $j++) {
                                     $item = $items[$j];
                                     if (!isset($item) || $item === "") {
                                         continue;
                                     }
                                     switch ($j) {
                                         case 0:
                                             //name
                                             $taxonomy_slug = sanitize_title($item);
                                             $insertarr["name"] = $item;
                                             break;
                                         case 1:
                                             //value
                                             $insertarr["value"] = $item;
                                             break;
                                         case 2:
                                             //is_visible
                                             $insertarr["is_visible"] = (int) $item;
                                             break;
                                         case 3:
                                             //is_variation
                                             $insertarr["is_variation"] = (int) $item;
                                             break;
                                         default:
                                             break;
                                     }
                                 }
                                 if (isset($patt[$taxonomy_slug])) {
                                     $patt[$taxonomy_slug]["name"] = $insertarr["name"];
                                     $patt[$taxonomy_slug]["value"] = $insertarr["value"];
                                     $patt[$taxonomy_slug]["is_visible"] = $insertarr["is_visible"];
                                     $patt[$taxonomy_slug]["is_variation"] = $insertarr["is_variation"];
                                     $patt[$taxonomy_slug]["is_taxonomy"] = 0;
                                     //											$patt[$taxonomy_slug]["position"] = count($patt);
                                 } else {
                                     $patt[$taxonomy_slug] = array();
                                     $patt[$taxonomy_slug]["name"] = $insertarr["name"];
                                     $patt[$taxonomy_slug]["value"] = $insertarr["value"];
                                     $patt[$taxonomy_slug]["is_visible"] = $insertarr["is_visible"];
                                     $patt[$taxonomy_slug]["is_variation"] = $insertarr["is_variation"];
                                     $patt[$taxonomy_slug]["is_taxonomy"] = 0;
                                     $patt[$taxonomy_slug]["position"] = count($patt);
                                 }
                                 $attrsaved[$taxonomy_slug] = 1;
                             }
                             foreach ($patt as $attrin => $attrval) {
                                 if (isset($attrval["is_taxonomy"]) && $attrval["is_taxonomy"] === 0) {
                                     if (!isset($attrsaved[$attrin])) {
                                         unset($patt[$attrin]);
                                     }
                                     //									 	for($j = 0; $j < count($attributes); $j++)
                                     //										{
                                     //											 $attr = $attributes[$j];
                                     //											 if($attr['name'] === $attrin)
                                     //											 	break;
                                     //										}
                                 }
                             }
                             update_post_meta($ID, '_product_attributes', $patt);
                             self::RefreshCustMetaKeys($ID, $attrsaved, $patt, true);
                         } else {
                             //variation
                             $attributessave = array();
                             $attributessave = explode('*****', $Row);
                             $attrsaved = array();
                             if ($attributessave) {
                                 for ($i = 0; $i < count($attributessave); $i++) {
                                     $itemsarr = $attributessave[$i];
                                     $insertarr = array();
                                     $attrslug = "attribute_";
                                     $attrvalue = "";
                                     if (!isset($itemsarr) || $itemsarr === "") {
                                         continue;
                                     }
                                     $items = explode('#####', $itemsarr);
                                     for ($j = 0; $j < count($items); $j++) {
                                         $item = $items[$j];
                                         if (!isset($item) || $item === "") {
                                             continue;
                                         }
                                         switch ($j) {
                                             case 0:
                                                 //name
                                                 $attrslug .= $item;
                                                 break;
                                             case 1:
                                                 //value
                                                 $attrvalue = $item;
                                                 break;
                                             default:
                                                 break;
                                         }
                                     }
                                     $attrsaved[$attrslug] = 1;
                                     update_post_meta($ID, $attrslug, $attrvalue);
                                 }
                             } else {
                                 $items = explode('#####', $itemsarr);
                                 $attrslug = "attribute_";
                                 $attrvalue = "";
                                 for ($j = 0; $j < count($items); $j++) {
                                     $item = $items[$j];
                                     if (!isset($item) || $item === "") {
                                         continue;
                                     }
                                     switch ($j) {
                                         case 0:
                                             //name
                                             $attrslug .= $item;
                                             break;
                                         case 1:
                                             //value
                                             $attrvalue = $item;
                                             break;
                                         default:
                                             break;
                                     }
                                 }
                                 $attrsaved[$attrslug] = 1;
                                 update_post_meta($ID, $attrslug, $attrvalue);
                             }
                             self::RefreshCustMetaKeys($ID, $attrsaved, $attributes, false);
                         }
                         break;
                     case "_stock_status":
                         if (function_exists('wc_update_product_stock_status')) {
                             wc_update_product_stock_status($ID, $Row);
                         } else {
                             update_post_meta($ID, $i, $Row);
                         }
                         break;
                     case "_stock":
                         if (function_exists('wc_update_product_stock')) {
                             wc_update_product_stock($ID, intval($Row));
                         } else {
                             update_post_meta($ID, $i, intval($Row));
                         }
                         //								$status = get_post_meta($ID,'_stock_status');
                         //								if($status !== 'outofstock')
                         //								update_post_meta( $ID , '_stock_status', 'instock');
                         //								wc_update_product_stock_status( $ID, 'instock' );
                     default:
                         if ($i !== 'ID' && $i !== 'post_parent' && $i !== 'parent') {
                             if (strpos($i, "attribute_pa_", 0) === 0 && strpos($i, "_visiblefp", 0) === FALSE) {
                                 //									return $i;
                                 self::HandleAttrs($ID, $parentid, $parentattrs_cache, $attributes, $Row, $i, count($data), $update_parent_attr);
                             } elseif (strpos($i, "attribute_pa_", 0) === 0 && strpos($i, "_visiblefp", 0) !== FALSE) {
                                 $query = "SELECT post_type FROM {$wpdb->posts} WHERE ID={$ID}";
                                 $ret = $wpdb->get_var($query);
                                 //									$arrret['i'] = $i;
                                 if ($ret === 'product') {
                                     $patt = get_post_meta($ID, '_product_attributes', true);
                                     $taxonomy_slug = "";
                                     $pos = strpos($i, "attribute_");
                                     if ($pos !== false) {
                                         $taxonomy_slug = substr_replace($i, "", $pos, strlen("attribute_"));
                                     }
                                     $taxonomy_slug = str_replace('_visiblefp', '', $taxonomy_slug);
                                     if (is_array($patt)) {
                                         if (isset($patt[$taxonomy_slug])) {
                                             $val = (int) $Row;
                                             if ($val & 1) {
                                                 $patt[$taxonomy_slug]["is_visible"] = 1;
                                             } else {
                                                 $patt[$taxonomy_slug]["is_visible"] = 0;
                                             }
                                             if ($val & 2) {
                                                 $patt[$taxonomy_slug]["is_variation"] = 1;
                                             } else {
                                                 $patt[$taxonomy_slug]["is_variation"] = 0;
                                             }
                                             update_post_meta($ID, '_product_attributes', $patt);
                                         }
                                     }
                                 }
                             } else {
                                 if (strpos($Row, ":", 0) !== FALSE && strpos($Row, ";", 0) !== FALSE && strpos($Row, "{", 0) !== FALSE && strpos($Row, "}", 0) !== FALSE) {
                                     $query = "SELECT meta_id FROM {$meta} WHERE post_id={$ID} AND meta_key='{$i}'";
                                     $ret = $wpdb->get_var($query);
                                     if ($ret === NULL) {
                                         $query = "INSERT INTO {$meta} (post_id,meta_key,meta_value)\r\n\t\t\t\t\t\t\t \t\t\t\t\t VALUES ({$ID},'{$i}','{$Row}');";
                                         $ret = $wpdb->query($query);
                                     } else {
                                         $query = "UPDATE {$meta} SET meta_value='" . $Row . "' WHERE meta_id={$ret}";
                                         $wpdb->query($query);
                                     }
                                 } else {
                                     update_post_meta($ID, $i, $Row);
                                 }
                             }
                         }
                         break;
                 }
             }
             if (array_key_exists('_stock_status', $arrrow) || array_key_exists('_manage_stock', $arrrow) || array_key_exists('_stock', $arrrow)) {
                 if (function_exists("wc_delete_product_transients")) {
                     wc_delete_product_transients($ID);
                     if ($parentid > 0) {
                         wc_delete_product_transients($parentid);
                     }
                 }
                 $newvar = new stdClass();
                 $newvar->ID = (string) $ID;
                 $newvar->_stock_status = get_post_meta($ID, '_stock_status', true);
                 $retarray[] = $newvar;
             }
             if (array_key_exists('_featured', $arrrow)) {
                 delete_transient('wc_featured_products');
             }
             if (array_key_exists('_sale_price', $arrrow) || array_key_exists('_regular_price', $arrrow) || array_key_exists('_sale_price_dates_from', $arrrow) || array_key_exists('_sale_price_dates_to', $arrrow)) {
                 self::HandlePriceUpdate($ID, $parentid, $arrrow);
                 if ($parentid > 0) {
                     //						if(function_exists("wc_delete_product_transients"))
                     //							wc_delete_product_transients($parentid);
                     if (!in_array($parentid, $update_vars_price)) {
                         $update_vars_price[] = $parentid;
                     }
                 } else {
                     if (function_exists("wc_delete_product_transients")) {
                         wc_delete_product_transients($ID);
                     }
                 }
             }
             self::CallWooAction($ID, $oldpost, $arrrow);
         }
     }
     foreach ($update_vars_price as $item_id) {
         self::HandleSaleRemove($item_id);
     }
     $attrarrays = array();
     if (is_array($attributes) && !empty($attributes)) {
         foreach ($attributes as $attr) {
             if (!property_exists($attr, 'name')) {
                 continue;
             }
             $attrarrays[] = 'pa_' . $attr->name;
         }
     }
     $bdontcheckusedfor = false;
     $curr_settings = get_option('w3exabe_settings');
     if (is_array($curr_settings)) {
         if (isset($curr_settings['dontcheckusedfor'])) {
             if ($curr_settings['dontcheckusedfor'] == 1) {
                 $bdontcheckusedfor = true;
             }
         }
     }
     self::WriteDebugInfo("loop number ", "", "before attr refresh");
     foreach ($data as $arrrow) {
         if (!is_array($arrrow)) {
             continue;
         }
         $ID = 0;
         if (array_key_exists('ID', $arrrow)) {
             $ID = (int) $arrrow['ID'];
             $parentid = 0;
             if (array_key_exists('post_parent', $arrrow)) {
                 $parentid = (int) $arrrow['post_parent'];
             }
             if ($parentid != 0) {
                 continue;
             }
             $updatemeta = false;
             foreach ($arrrow as $i => $Row) {
                 if (strpos($i, "attribute_pa_", 0) === 0) {
                     $updatemeta = true;
                     break;
                 }
             }
             if ($updatemeta) {
                 $bvariable = false;
                 if (is_object_in_term($ID, 'product_type', 'variable')) {
                     $bvariable = true;
                 }
                 $patt = get_post_meta($ID, '_product_attributes', true);
                 if (!is_array($patt)) {
                     $patt = array();
                 }
                 $attrs = wp_get_object_terms($ID, $attrarrays);
                 if (is_array($attrs)) {
                     //							foreach($patt as $key => $value)
                     //							{
                     //								$haskey = false;
                     //								foreach($attrs as $attr_obj)
                     //								{
                     //									if(!is_object($attr_obj)) continue;
                     //									if(!property_exists($attr_obj,'taxonomy')) continue;
                     //									if($key == $attr_obj->taxonomy)
                     //									{
                     //										$haskey = true;
                     //										break;
                     //									}
                     //								}
                     //								if(!$haskey)
                     //								{
                     //									unset($patt[$key]);
                     //								}
                     //							}
                     $existing = array();
                     foreach ($attrs as $attr_obj) {
                         if (!is_object($attr_obj)) {
                             continue;
                         }
                         if (!property_exists($attr_obj, 'term_id')) {
                             continue;
                         }
                         if (!property_exists($attr_obj, 'taxonomy')) {
                             continue;
                         }
                         if (!in_array($attr_obj->taxonomy, $existing)) {
                             $existing[] = $attr_obj->taxonomy;
                         }
                         if (!isset($patt[$attr_obj->taxonomy])) {
                             $patt[$attr_obj->taxonomy] = array();
                             $patt[$attr_obj->taxonomy]["name"] = $attr_obj->taxonomy;
                             $patt[$attr_obj->taxonomy]["is_visible"] = 0;
                             $patt[$attr_obj->taxonomy]["is_taxonomy"] = 1;
                             if ($bvariable && !$bdontcheckusedfor) {
                                 $patt[$attr_obj->taxonomy]["is_variation"] = 1;
                             } else {
                                 $patt[$attr_obj->taxonomy]["is_variation"] = 0;
                             }
                             $patt[$attr_obj->taxonomy]["value"] = "";
                             $patt[$attr_obj->taxonomy]["position"] = count($patt);
                         }
                     }
                     //check for deleted terms
                     foreach ($patt as $patt_name => $patt_item) {
                         if (is_array($patt_item)) {
                             if (isset($patt_item["is_taxonomy"]) && $patt_item["is_taxonomy"] == 1) {
                                 if (!in_array($patt_name, $existing)) {
                                     unset($patt[$patt_name]);
                                 }
                             }
                         }
                     }
                     update_post_meta($ID, '_product_attributes', $patt);
                     self::CallWooAction($ID);
                 }
             }
         }
     }
     foreach ($update_parent_attr as $parid => $attrarrays) {
         $newpar = new stdClass();
         $newpar->ID = $parid;
         $newpar->post_parent = "0";
         $attrs = wp_get_object_terms($parid, $attrarrays);
         if (is_array($attrs)) {
             foreach ($attrs as $attr_obj) {
                 if (!is_object($attr_obj)) {
                     continue;
                 }
                 if (!property_exists($attr_obj, 'term_id')) {
                     continue;
                 }
                 if (!property_exists($attr_obj, 'name')) {
                     continue;
                 }
                 if (!property_exists($attr_obj, 'taxonomy')) {
                     continue;
                 }
                 $attr_prop = 'attribute_' . $attr_obj->taxonomy;
                 if (!property_exists($newpar, $attr_prop)) {
                     $newpar->{$attr_prop} = $attr_obj->name;
                     self::UpdateParentMeta($parid, $attr_obj->taxonomy);
                     $newpar->{$attr_prop . '_visiblefp'} = 2;
                 } else {
                     $newpar->{$attr_prop} = $newpar->{$attr_prop} . ', ' . $attr_obj->name;
                 }
                 $attr_ids = 'attribute_' . $attr_obj->taxonomy . '_ids';
                 if (!property_exists($newpar, $attr_ids)) {
                     $newpar->{$attr_ids} = (string) $attr_obj->term_id;
                 } else {
                     $newpar->{$attr_ids} = $newpar->{$attr_ids} . ',' . (string) $attr_obj->term_id;
                 }
             }
         }
         $retarray[] = $newpar;
     }
     self::WriteDebugInfo("loop number ", "", "after attr refresh");
     return $retarray;
 }