/** * Reduce stock levels for items within an order. * @since 2.7.0 * @param int $order_id */ function wc_reduce_stock_levels($order_id) { $order = wc_get_order($order_id); if ('yes' === get_option('woocommerce_manage_stock') && $order && apply_filters('woocommerce_can_reduce_order_stock', true, $order) && sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { if ($item->is_type('line_item') && ($product = $item->get_product()) && $product->managing_stock()) { $qty = apply_filters('woocommerce_order_item_quantity', $item->get_quantity(), $order, $item); $item_name = $product->get_formatted_name(); $new_stock = wc_update_product_stock($product, $qty, 'decrease'); if (!is_wp_error($new_stock)) { /* translators: 1: item name 2: old stock quantity 3: new stock quantity */ $order->add_order_note(sprintf(__('%1$s stock reduced from %2$s to %3$s.', 'woocommerce'), $item_name, $new_stock + $qty, $new_stock)); if ('' !== get_option('woocommerce_notify_no_stock_amount') && $new_stock <= get_option('woocommerce_notify_no_stock_amount')) { do_action('woocommerce_no_stock', $product); } elseif ('' !== get_option('woocommerce_notify_low_stock_amount') && $new_stock <= get_option('woocommerce_notify_low_stock_amount')) { do_action('woocommerce_low_stock', $product); } if ($new_stock < 0) { do_action('woocommerce_product_on_backorder', array('product' => $product, 'order_id' => $order_id, 'quantity' => $qty_ordered)); } } } } do_action('woocommerce_reduce_order_stock', $order); } }
/** * Test wc_update_product_stock() * * @since 2.3 */ public function test_wc_update_product_stock() { // Create product $product = \WC_Helper_Product::create_simple_product(); update_post_meta($product->id, '_manage_stock', 'yes'); wc_update_product_stock($product->id, 5); $this->assertEquals(5, $product->stock); // Delete Product \WC_Helper_Product::delete_product($product->id); }
/** * 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; }
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); }
/** * @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; } } } }
/** * 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); }
/** * 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 variations via AJAX */ public static function bulk_edit_variations() { ob_start(); check_ajax_referer('bulk-edit-variations', 'security'); // Check permissions again and make sure we have what we need if (!current_user_can('edit_products') || empty($_POST['product_id']) || empty($_POST['bulk_action'])) { die(-1); } global $wpdb; $product_id = absint($_POST['product_id']); $bulk_action = wc_clean($_POST['bulk_action']); $data = !empty($_POST['data']) ? array_map('wc_clean', $_POST['data']) : array(); $variations = array(); if (apply_filters('woocommerce_bulk_edit_variations_need_children', !in_array($bulk_action, array('variable_weight', 'variable_length', 'variable_width', 'variable_height')))) { $variations = get_posts(array('post_parent' => $product_id, 'posts_per_page' => -1, 'post_type' => 'product_variation', 'fields' => 'ids', 'post_status' => array('publish', 'private'))); } switch ($bulk_action) { case 'toggle_enabled': foreach ($variations as $variation_id) { $post_status = get_post_status($variation_id); $new_status = 'private' === $post_status ? 'publish' : 'private'; $wpdb->update($wpdb->posts, array('post_status' => $new_status), array('ID' => $variation_id)); } break; case 'toggle_downloadable': foreach ($variations as $variation_id) { $_downloadable = get_post_meta($variation_id, '_downloadable', true); $is_downloadable = 'no' === $_downloadable ? 'yes' : 'no'; update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable)); } break; case 'toggle_virtual': foreach ($variations as $variation_id) { $_virtual = get_post_meta($variation_id, '_virtual', true); $is_virtual = 'no' === $_virtual ? 'yes' : 'no'; update_post_meta($variation_id, '_virtual', wc_clean($is_virtual)); } break; case 'toggle_manage_stock': foreach ($variations as $variation_id) { $_manage_stock = get_post_meta($variation_id, '_manage_stock', true); $is_manage_stock = 'no' === $_manage_stock ? 'yes' : 'no'; update_post_meta($variation_id, '_manage_stock', wc_clean($is_manage_stock)); } break; case 'variable_regular_price': case 'variable_sale_price': if (empty($data['value'])) { break; } $field = str_replace('variable', '', $bulk_action); foreach ($variations as $variation_id) { // Price fields $regular_price = '_regular_price' === $field ? $data['value'] : get_post_meta($variation_id, '_regular_price', true); $sale_price = '_sale_price' === $field ? $data['value'] : get_post_meta($variation_id, '_sale_price', true); // Date fields $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true); $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true); $date_from = !empty($date_from) ? date('Y-m-d', $date_from) : ''; $date_to = !empty($date_to) ? date('Y-m-d', $date_to) : ''; _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to); } break; case 'variable_stock': if (empty($data['value'])) { break; } $value = wc_clean($data['value']); foreach ($variations as $variation_id) { if ('yes' === get_post_meta($variation_id, '_manage_stock', true)) { wc_update_product_stock($variation_id, wc_stock_amount($value)); } else { delete_post_meta($variation_id, '_stock'); } } break; case 'variable_weight': case 'variable_length': case 'variable_width': case 'variable_height': if (empty($data['value'])) { break; } $value = wc_clean($data['value']); $field = str_replace('variable', '', $bulk_action); $wpdb->query($wpdb->prepare("\n\t\t\t\t\tUPDATE {$wpdb->postmeta} AS postmeta\n\t\t\t\t\tINNER JOIN {$wpdb->posts} AS posts ON posts.post_parent = %d\n\t\t\t\t\tSET postmeta.meta_value = %s\n\t\t\t\t\tWHERE postmeta.meta_key = '%s'\n\t\t\t\t\tAND postmeta.post_id = posts.ID\n\t\t\t\t ", $product_id, $value, $field)); break; case 'variable_download_limit': case 'variable_download_expiry': if (empty($data['value'])) { break; } $value = wc_clean($data['value']); $field = str_replace('variable', '', $bulk_action); foreach ($variations as $variation_id) { if ('yes' === get_post_meta($variation_id, '_downloadable', true)) { update_post_meta($variation_id, $field, $value); } else { update_post_meta($variation_id, $field, ''); } } break; case 'delete_all': if (isset($data['allowed']) && 'true' === $data['allowed']) { foreach ($variations as $variation_id) { wp_delete_post($variation_id); } } break; case 'variable_regular_price_increase': case 'variable_regular_price_decrease': case 'variable_sale_price_increase': case 'variable_sale_price_decrease': if (empty($data['value'])) { break; } $field = str_replace(array('variable', '_increase', '_decrease'), '', $bulk_action); $operator = 'increase' === substr($bulk_action, -8) ? +1 : -1; foreach ($variations as $variation_id) { // Price fields $regular_price = get_post_meta($variation_id, '_regular_price', true); $sale_price = get_post_meta($variation_id, '_sale_price', true); // Date fields $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true); $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true); $date_from = !empty($date_from) ? date('Y-m-d', $date_from) : ''; $date_to = !empty($date_to) ? date('Y-m-d', $date_to) : ''; if ('%' === substr($data['value'], -1)) { $percent = wc_format_decimal(substr($data['value'], 0, -1)); if ('_regular_price' === $field) { $regular_price += $regular_price / 100 * $percent * $operator; } else { $sale_price += $sale_price / 100 * $percent * $operator; } } else { if ('_regular_price' === $field) { $regular_price += $data['value']; } else { $sale_price += $data['value']; } } _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to); } break; case 'variable_sale_schedule': if (!isset($data['date_from']) && !isset($data['date_to'])) { break; } foreach ($variations as $variation_id) { // Price fields $regular_price = get_post_meta($variation_id, '_regular_price', true); $sale_price = get_post_meta($variation_id, '_sale_price', true); // Date fields $date_from = get_post_meta($variation_id, '_sale_price_dates_from', true); $date_to = get_post_meta($variation_id, '_sale_price_dates_to', true); if ('false' === $data['date_from']) { $date_from = !empty($date_from) ? date('Y-m-d', $date_from) : ''; } else { $date_from = $data['date_from']; } if ('false' === $data['date_to']) { $date_to = !empty($date_to) ? date('Y-m-d', $date_to) : ''; } else { $date_to = $data['date_to']; } _wc_save_product_price($variation_id, $regular_price, $sale_price, $date_from, $date_to); } break; default: do_action('woocommerce_bulk_edit_variations_default', $bulk_action, $data, $product_id, $variations); break; } do_action('woocommerce_bulk_edit_variations', $bulk_action, $data, $product_id, $variations); // Sync and update transients WC_Product_Variable::sync($product_id); wc_delete_product_transients($product_id); die; }
/** * Update product stock * * Handles to Update Product Stock * * @package WooCommerce - PDF Vouchers * @since 2.4.0 */ public function woo_vou_update_product_stock($product_id = '', $variation_id = '', $voucher_codes = array()) { //Total avialable voucher code $avail_total_codes = count($voucher_codes); if (!empty($variation_id)) { wc_update_product_stock($variation_id, $avail_total_codes); } else { wc_update_product_stock($product_id, $avail_total_codes); } }
public function update_post_metas() { text('Started Updating Product Meta '); text('current product type : ' . $this->current_product_type); wp_set_object_terms($this->current_product_id, $this->current_product_type, 'product_type'); if ($this->current_product_type == 'simple') { $this->set_post_meta($this->current_product_id, $this->current_product['variants'][0]); $this->add_vendor(); $this->set_product_attribute($this->created_attribute[product_vendor_term], $this->current_product['vendor'], 0, 0, 1, 1); if (isset($this->current_product['variants'][0]['inventory_quantity']) && $this->current_product['variants'][0]['inventory_quantity'] != null) { wc_update_product_stock($this->current_product_id, intval($this->current_product['variants'][0]['inventory_quantity'])); } else { wc_update_product_stock($this->current_product_id, intval(0)); } text('Adding Product Type '); $collections = $this->checkCollection($this->current_product['id']); if (!empty($collections)) { foreach ($collections as $cname) { $term_id = $this->create_tax_term($cname, $this->created_attribute[product_type_term]); wp_set_post_terms($this->current_product_id, $term_id, $this->created_attribute[product_type_term]); } $this->set_product_attribute($this->created_attribute[product_type_term], implode(",", $collections), 0, 0, 1, 1); } } else { if ($this->current_product_type == 'variable') { $others = array(); $collections_set = array(); $ab_key = $this->get_varients_attribute_key(); $custom_meta = array(); foreach ($this->current_product['variants'] as $varK => $varV) { $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), $varV['id'], esc_html($this->current_product['title'])); $collections = $this->checkCollection($varV['id']); $new_variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => product_status, 'post_author' => product_author, 'post_parent' => $this->current_product_id, 'post_type' => product_varient_post_type); $variation_id = wp_insert_post($new_variation); do_action('woocommerce_create_product_variation', $variation_id); if (!empty($collections)) { foreach ($collections as $cols) { $collections_set[] = $collections; } $custom_meta[$ab_key['type']] = sanitize_title(stripslashes($collections[0])); } if (isset($varV['inventory_quantity']) && $varV['inventory_quantity'] != null) { wc_update_product_stock($variation_id, intval($varV['inventory_quantity'])); } else { wc_update_product_stock($variation_id, intval(0)); } if (!empty($varV['option1']) && $varV['option1'] !== null) { $others[$this->checkVariationValue($varV['option1'])][] = $varV['option1']; } if (!empty($varV['option2']) && $varV['option2'] !== null) { $others[$this->checkVariationValue($varV['option2'])][] = $varV['option2']; } if (!empty($varV['option3']) && $varV['option3'] !== null) { $others[$this->checkVariationValue($varV['option3'])][] = $varV['option3']; } $this->set_post_meta($variation_id, $varV, $custom_meta); } } } $this->add_vendor(); $this->set_product_attribute($this->created_attribute[product_vendor_term], $this->current_product['vendor'], 0, 0, 1, 1); $collections = $this->checkCollection($this->current_product['id']); if (!empty($collections)) { foreach ($collections as $cname) { $term_id = $this->create_tax_term($cname, $this->created_attribute[product_type_term]); wp_set_post_terms($this->current_product_id, $term_id, $this->created_attribute[product_type_term]); } $this->set_product_attribute($this->created_attribute[product_type_term], implode(",", $collections), 0, 0, 1, 1); } if (!empty($others)) { foreach ($others as $othk => $othv) { if (is_array($othv)) { foreach ($othv as $v) { $this->create_tax_term($v, $this->created_attribute[$othk]); } } wp_set_object_terms($this->current_product_id, $othv, $this->created_attribute[$othk]); $this->set_product_attribute($this->created_attribute[$othk], implode(',', $othv)); } } $custom_meta['_product_attributes'] = $this->current_product_attribute; $this->set_post_meta($this->current_product_id, $varV, $custom_meta); text('Finished Updating Product Meta '); }
/** * Save Metabox Data * * Handles to save metabox details * to database * * @package WooCommerce - PDF Vouchers * @since 1.0.0 */ public function woo_vou_product_save_data($post_id, $post) { global $post_type; // get prefix $prefix = WOO_VOU_META_PREFIX; //is downloadable $is_downloadable = get_post_meta($post_id, '_downloadable', true); // Getting product type $product_type = !empty($_POST['product-type']) ? $_POST['product-type'] : ''; // Enable Voucher Codes $woo_vou_enable = !empty($_POST[$prefix . 'enable']) ? 'yes' : ''; // get Pdf template $woo_vou_pdf_template = isset($_POST[$prefix . 'pdf_template']) ? $_POST[$prefix . 'pdf_template'] : ''; // Usability $woo_vou_using_type = isset($_POST[$prefix . 'using_type']) ? $_POST[$prefix . 'using_type'] : ''; // get logo $woo_vou_logo = isset($_POST[$prefix . 'logo']) ? $_POST[$prefix . 'logo'] : ''; // get address $woo_vou_address_phone = isset($_POST[$prefix . 'address_phone']) ? $_POST[$prefix . 'address_phone'] : ''; // get website $woo_vou_website = isset($_POST[$prefix . 'website']) ? $_POST[$prefix . 'website'] : ''; // get redeem instructions $woo_vou_how_to_use = isset($_POST[$prefix . 'how_to_use']) ? $_POST[$prefix . 'how_to_use'] : ''; // enable recipient name $enable_recipient_name = !empty($_POST[$prefix . 'enable_recipient_name']) ? 'yes' : ''; $recipient_name_max_length = !empty($_POST[$prefix . 'recipient_name_max_length']) && is_numeric($_POST[$prefix . 'recipient_name_max_length']) ? trim(round($_POST[$prefix . 'recipient_name_max_length'])) : ''; $recipient_name_label = !empty($_POST[$prefix . 'recipient_name_label']) ? trim($_POST[$prefix . 'recipient_name_label']) : ''; $recipient_name_is_required = !empty($_POST[$prefix . 'recipient_name_is_required']) ? 'yes' : ''; // enable recipient email $woo_vou_recipient_email = !empty($_POST[$prefix . 'enable_recipient_email']) ? 'yes' : ''; $recipient_email_label = !empty($_POST[$prefix . 'recipient_email_label']) ? trim($_POST[$prefix . 'recipient_email_label']) : ''; $recipient_email_is_required = !empty($_POST[$prefix . 'recipient_email_is_required']) ? 'yes' : ''; // enable recipient message $enable_recipient_message = !empty($_POST[$prefix . 'enable_recipient_message']) ? 'yes' : ''; $recipient_message_max_length = !empty($_POST[$prefix . 'recipient_message_max_length']) && is_numeric($_POST[$prefix . 'recipient_message_max_length']) ? trim(round($_POST[$prefix . 'recipient_message_max_length'])) : ''; $recipient_message_label = !empty($_POST[$prefix . 'recipient_message_label']) ? trim($_POST[$prefix . 'recipient_message_label']) : ''; $recipient_message_is_required = !empty($_POST[$prefix . 'recipient_message_is_required']) ? 'yes' : ''; // Check if downloadable is on or variable product then set voucher enable option otherwise not set if ($is_downloadable == 'yes' || $product_type == 'variable') { $enable_voucher = $woo_vou_enable; } else { $enable_voucher = ''; } // Getting downloadable variable //$variable_is_downloadable = !empty($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array(); update_post_meta($post_id, $prefix . 'enable', $enable_voucher); //Recipient Name Detail Update update_post_meta($post_id, $prefix . 'enable_recipient_name', $enable_recipient_name); update_post_meta($post_id, $prefix . 'recipient_name_max_length', $recipient_name_max_length); update_post_meta($post_id, $prefix . 'recipient_name_label', $recipient_name_label); update_post_meta($post_id, $prefix . 'recipient_name_is_required', $recipient_name_is_required); //Recipient Email Detail Update update_post_meta($post_id, $prefix . 'enable_recipient_email', $woo_vou_recipient_email); update_post_meta($post_id, $prefix . 'recipient_email_label', $recipient_email_label); update_post_meta($post_id, $prefix . 'recipient_email_is_required', $recipient_email_is_required); //Recipient Message Detail Update update_post_meta($post_id, $prefix . 'enable_recipient_message', $enable_recipient_message); update_post_meta($post_id, $prefix . 'recipient_message_max_length', $recipient_message_max_length); update_post_meta($post_id, $prefix . 'recipient_message_label', $recipient_message_label); update_post_meta($post_id, $prefix . 'recipient_message_is_required', $recipient_message_is_required); // PDF Template update_post_meta($post_id, $prefix . 'pdf_template', $woo_vou_pdf_template); // Vendor User update_post_meta($post_id, $prefix . 'vendor_user', $_POST[$prefix . 'vendor_user']); //expire type if (isset($_POST[$prefix . 'exp_type'])) { update_post_meta($post_id, $prefix . 'exp_type', $_POST[$prefix . 'exp_type']); } update_post_meta($post_id, $prefix . 'days_diff', $_POST[$prefix . 'days_diff']); $custom_days = !empty($_POST[$prefix . 'custom_days']) && is_numeric($_POST[$prefix . 'custom_days']) ? trim(round($_POST[$prefix . 'custom_days'])) : ''; update_post_meta($post_id, $prefix . 'custom_days', $custom_days); // Start Date $start_date = $_POST[$prefix . 'start_date']; if (!empty($start_date)) { $start_date = strtotime($this->model->woo_vou_escape_slashes_deep($start_date)); $start_date = date('Y-m-d H:i:s', $start_date); } update_post_meta($post_id, $prefix . 'start_date', $start_date); // Expiration Date $exp_date = $_POST[$prefix . 'exp_date']; if (!empty($exp_date)) { $exp_date = strtotime($this->model->woo_vou_escape_slashes_deep($exp_date)); $exp_date = date('Y-m-d H:i:s', $exp_date); } update_post_meta($post_id, $prefix . 'exp_date', $exp_date); // Voucher Codes $voucher_codes = isset($_POST[$prefix . 'codes']) ? $this->model->woo_vou_escape_slashes_deep($_POST[$prefix . 'codes']) : ''; update_post_meta($post_id, $prefix . 'codes', $voucher_codes); $usability = $woo_vou_using_type; if (isset($_POST[$prefix . 'vendor_user']) && !empty($_POST[$prefix . 'vendor_user']) && $usability == '') { //if vendor user is set and usability is default $usability = get_user_meta($_POST[$prefix . 'vendor_user'], $prefix . 'using_type', true); } // If usability is default then take it from setting if ($usability == '') { $usability = get_option('vou_pdf_usability'); } update_post_meta($post_id, $prefix . 'using_type', $woo_vou_using_type); // vendor's Logo update_post_meta($post_id, $prefix . 'logo', $woo_vou_logo); // Vendor's Address update_post_meta($post_id, $prefix . 'address_phone', $this->model->woo_vou_escape_slashes_deep($woo_vou_address_phone, true, true)); // Website URL update_post_meta($post_id, $prefix . 'website', $this->model->woo_vou_escape_slashes_deep($woo_vou_website)); // Redeem Instructions update_post_meta($post_id, $prefix . 'how_to_use', $this->model->woo_vou_escape_slashes_deep($woo_vou_how_to_use, true, true)); // update available products count on bases of entered voucher codes if (isset($_POST[$prefix . 'codes']) && $enable_voucher == 'yes') { $voucount = ''; $vouchercodes = trim($_POST[$prefix . 'codes'], ','); if (!empty($vouchercodes)) { $vouchercodes = explode(',', $vouchercodes); $voucount = count($vouchercodes); } if (empty($usability)) { // using type is only one time $avail_total = empty($voucount) ? '0' : $voucount; // Getting variable product id $variable_post_id = !empty($_POST['variable_post_id']) ? $_POST['variable_post_id'] : array(); // If product is variable and id's are not blank then update their quantity with blank if ($product_type == 'variable' && !empty($variable_post_id)) { // set flag false $variable_code_flag = false; foreach ($variable_post_id as $variable_post) { $variable_is_downloadable = get_post_meta($variable_post, '_downloadable', true); $variable_codes = get_post_meta($variable_post, $prefix . 'codes', true); if ($variable_is_downloadable == 'yes' && !empty($variable_codes)) { // if variation is set as downloadable and vochers codes set at variation level $variable_code_flag = true; } } if ($variable_code_flag == true) { // mark this product as variable voucher so we consider it to take vouchers from variations update_post_meta($post_id, $prefix . 'is_variable_voucher', '1'); } else { update_post_meta($post_id, $prefix . 'is_variable_voucher', ''); } foreach ($variable_post_id as $variable_post) { if ($variable_code_flag != true) { // if there no voucher codes set on variation level // update variation manage stock as no update_post_meta($variable_post, '_manage_stock', 'no'); // Update variation stock qty with blank update_post_meta($variable_post, '_stock', ''); // Update variation downloadable with yes update_post_meta($variable_post, '_downloadable', 'yes'); } else { //update manage stock with yes update_post_meta($variable_post, '_manage_stock', 'yes'); $variable_voucount = ''; $variable_codes = get_post_meta($variable_post, $prefix . 'codes', true); $vouchercodes = trim($variable_codes, ','); if (!empty($vouchercodes)) { $vouchercodes = explode(',', $vouchercodes); $variable_voucount = count($vouchercodes); } $variable_avail_total = empty($variable_voucount) ? '0' : $variable_voucount; //update available count on bases of //update_post_meta( $variable_post, '_stock', $variable_avail_total ); wc_update_product_stock($variable_post, $variable_avail_total); } } } //update manage stock with yes update_post_meta($post_id, '_manage_stock', 'yes'); //update available count on bases of //update_post_meta( $post_id, '_stock', $avail_total ); wc_update_product_stock($post_id, $avail_total); } } //update location and map links $availlocations = array(); if (isset($_POST[$prefix . 'locations'])) { $locations = $_POST[$prefix . 'locations']; $maplinks = $_POST[$prefix . 'map_link']; for ($i = 0; $i < count($locations); $i++) { if (!empty($locations[$i]) || !empty($maplinks[$i])) { //if location or map link is not empty then $availlocations[$i][$prefix . 'locations'] = $this->model->woo_vou_escape_slashes_deep($locations[$i], true, true); $availlocations[$i][$prefix . 'map_link'] = $this->model->woo_vou_escape_slashes_deep($maplinks[$i]); } } } //update location and map links update_post_meta($post_id, $prefix . 'avail_locations', $availlocations); }
/** * 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); }
/** * Test wc_update_product_stock(). * * @since 2.3 */ public function test_wc_update_product_stock() { // Create product $product = WC_Helper_Product::create_simple_product(); update_post_meta($product->get_id(), '_manage_stock', 'yes'); wc_update_product_stock($product->get_id(), 5); $product = new WC_Product_Simple($product->get_id()); $this->assertEquals(5, $product->get_stock_quantity()); // Delete Product WC_Helper_Product::delete_product($product->get_id()); }
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; }
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_mrp_var = $_POST['_mrp_var']; $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_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_virtual = isset($variable_is_virtual[$i]) ? 'yes' : 'no'; $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no'; $manage_stock = isset($variable_stock[$i]) ? 'yes' : 'no'; // Enabled or disabled $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private'; // 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); } // Update post meta update_post_meta($variation_id, '_sku', wc_clean($variable_sku[$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', wc_clean($manage_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])); } // Stock handling if (isset($variable_stock[$i])) { wc_update_product_stock($variation_id, wc_clean($variable_stock[$i])); } // Price handling $mrp = wc_format_decimal($variable_mrp_var[$i]); $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); update_post_meta($variation_id, '_list_price_mrp', $mrp); // 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'); // Remove old taxonomies attributes so data is kept up to date if ($variation_id) { $wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND post_id = %d;", $variation_id)); wp_cache_delete($variation_id, 'post_meta'); } // Update taxonomies foreach ($attributes as $attribute) { if ($attribute['is_variation']) { // Don't use wc_clean as it destroys sanitized characters if (isset($_POST['attribute_' . sanitize_title($attribute['name'])][$i])) { $value = sanitize_title(trim(stripslashes($_POST['attribute_' . sanitize_title($attribute['name'])][$i]))); } else { $value = ''; } update_post_meta($variation_id, 'attribute_' . sanitize_title($attribute['name']), $value); } } 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); }
/** * Increase stock level of the product. * * @deprecated 2.7.0 * @param int $amount Amount to increase by. Default 1. * @return int new stock level */ public function increase_stock($amount = 1) { wc_deprecated_function('WC_Product::increase_stock', '2.7', 'wc_update_product_stock'); wc_update_product_stock($this, $amount, 'increase'); }
function invokeListInventorySupplyByNextToken(FBAInventoryServiceMWS_Interface $service, $request) { try { $response = $service->listInventorySupplyByNextToken($request); if ($response->isSetListInventorySupplyByNextTokenResult()) { $listInventorySupplyByNextTokenResult = $response->getListInventorySupplyByNextTokenResult(); if ($listInventorySupplyByNextTokenResult->isSetInventorySupplyList()) { $inventorySupplyList = $listInventorySupplyByNextTokenResult->getInventorySupplyList(); $memberList = $inventorySupplyList->getmember(); $countResult = count($memberList); $level = "Neutral"; $category = "Inventory"; $title = "Update Inventory (Next Token)"; if ($listInventorySupplyByNextTokenResult->isSetNextToken()) { $info = $countResult . " Products Retrieved, Getting more with next token..."; } else { $info = $countResult . " Products Retrieved."; } AmzFBA_Woo_Log($level, $category, $title, $info); foreach ($memberList as $member) { $inventory_level = $member->getInStockSupplyQuantity(); $sku = $member->getSellerSKU(); AmzFBA_Woo_install_data($sku, $inventory_level); $ProductID = GetIdFromSKU($sku); if ($ProductID != '') { // Sharad: adding logs AmzFBA_Woo_Log($level, $category, $title, "New level for [" . $sku . "] is " . $inventory_level); wc_update_product_stock($ProductID, $inventory_level); } } } if ($listInventorySupplyByNextTokenResult->isSetNextToken()) { $NextToken = $listInventorySupplyByNextTokenResult->getNextToken(); ListInventorySupplyByNextToken($NextToken); } } } catch (FBAInventoryServiceMWS_Exception $ex) { // echo("XML: " . $ex->getXML() . "\n"); $level = "Bad"; $category = "Inventory"; $title = "Retrieve Inventory Error (Next Token)"; $info = "Caught Exception: " . $ex->getMessage() . " | Response Status Code: " . $ex->getStatusCode() . " | Error Code: " . $ex->getErrorCode() . " | Error Type: " . $ex->getErrorType() . " | Request ID: " . $ex->getRequestId(); AmzFBA_Woo_Log($level, $category, $title, $info); SendErrorEmail($category, $info); } catch (Exception $e) { HandleGenericException("Inventory", $e); } }
/** * Updates the global stock level and individual product inventories for any ticket products * that utilize global stock. * * @param int $event_id * @param int $stock_level */ public function stock_update_global_tickets($event_id, $stock_level) { $woo_tickets = Tribe__Tickets_Plus__Commerce__WooCommerce__Main::get_instance(); foreach ($woo_tickets->get_tickets($event_id) as $ticket) { /** * @var Tribe__Tickets__Ticket_Object $ticket */ if (Tribe__Tickets__Global_Stock::OWN_STOCK_MODE === $ticket->global_stock_mode()) { continue; } wc_update_product_stock($ticket->ID, $stock_level); } }
/** * Bulk action - Set Stock * @access private * @param array $variations * @param array $data */ private static function variation_bulk_action_variable_stock($variations, $data) { if (empty($data['value'])) { break; } $value = wc_clean($data['value']); if ($value) { foreach ($variations as $variation_id) { if ('yes' === get_post_meta($variation_id, '_manage_stock', true)) { wc_update_product_stock($variation_id, wc_stock_amount($value)); } else { delete_post_meta($variation_id, '_stock'); } } } }
/** * 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; }
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; }