sync_stock_status() public static method

Sync parent stock status with the status of all children and save.
public static sync_stock_status ( WC_Product | integer $product, boolean $save = true ) : WC_Product
$product WC_Product | integer Product object or ID for which you wish to sync.
$save boolean If true, the prouduct object will be saved to the DB before returning it.
return WC_Product Synced product object.
Ejemplo n.º 1
1
 /**
  * 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.
  */
 public static function save($post_id, $post)
 {
     global $wpdb;
     // Add any default post meta
     add_post_meta($post_id, 'total_sales', '0', true);
     // Get types
     $product_type = empty($_POST['product-type']) ? 'simple' : sanitize_title(stripslashes($_POST['product-type']));
     $is_downloadable = isset($_POST['_downloadable']) ? 'yes' : 'no';
     $is_virtual = isset($_POST['_virtual']) ? 'yes' : 'no';
     // Product type + Downloadable/Virtual
     wp_set_object_terms($post_id, $product_type, 'product_type');
     update_post_meta($post_id, '_downloadable', $is_downloadable);
     update_post_meta($post_id, '_virtual', $is_virtual);
     // Update post meta
     if (isset($_POST['_tax_status'])) {
         update_post_meta($post_id, '_tax_status', wc_clean($_POST['_tax_status']));
     }
     if (isset($_POST['_tax_class'])) {
         update_post_meta($post_id, '_tax_class', wc_clean($_POST['_tax_class']));
     }
     if (isset($_POST['_purchase_note'])) {
         update_post_meta($post_id, '_purchase_note', wp_kses_post(stripslashes($_POST['_purchase_note'])));
     }
     // Featured
     if (update_post_meta($post_id, '_featured', isset($_POST['_featured']) ? 'yes' : 'no')) {
         delete_transient('wc_featured_products');
     }
     // Dimensions
     if ('no' == $is_virtual) {
         if (isset($_POST['_weight'])) {
             update_post_meta($post_id, '_weight', '' === $_POST['_weight'] ? '' : wc_format_decimal($_POST['_weight']));
         }
         if (isset($_POST['_length'])) {
             update_post_meta($post_id, '_length', '' === $_POST['_length'] ? '' : wc_format_decimal($_POST['_length']));
         }
         if (isset($_POST['_width'])) {
             update_post_meta($post_id, '_width', '' === $_POST['_width'] ? '' : wc_format_decimal($_POST['_width']));
         }
         if (isset($_POST['_height'])) {
             update_post_meta($post_id, '_height', '' === $_POST['_height'] ? '' : wc_format_decimal($_POST['_height']));
         }
     } else {
         update_post_meta($post_id, '_weight', '');
         update_post_meta($post_id, '_length', '');
         update_post_meta($post_id, '_width', '');
         update_post_meta($post_id, '_height', '');
     }
     // Save shipping class
     $product_shipping_class = $_POST['product_shipping_class'] > 0 && $product_type != 'external' ? absint($_POST['product_shipping_class']) : '';
     wp_set_object_terms($post_id, $product_shipping_class, 'product_shipping_class');
     // Unique SKU
     $sku = get_post_meta($post_id, '_sku', true);
     $new_sku = (string) wc_clean($_POST['_sku']);
     if ('' == $new_sku) {
         update_post_meta($post_id, '_sku', '');
     } elseif ($new_sku !== $sku) {
         if (!empty($new_sku)) {
             $unique_sku = wc_product_has_unique_sku($post_id, $new_sku);
             if (!$unique_sku) {
                 WC_Admin_Meta_Boxes::add_error(__('Product SKU must be unique.', 'woocommerce'));
             } else {
                 update_post_meta($post_id, '_sku', $new_sku);
             }
         } else {
             update_post_meta($post_id, '_sku', '');
         }
     }
     // Save Attributes
     $attributes = array();
     if (isset($_POST['attribute_names']) && isset($_POST['attribute_values'])) {
         $attribute_names = $_POST['attribute_names'];
         $attribute_values = $_POST['attribute_values'];
         if (isset($_POST['attribute_visibility'])) {
             $attribute_visibility = $_POST['attribute_visibility'];
         }
         if (isset($_POST['attribute_variation'])) {
             $attribute_variation = $_POST['attribute_variation'];
         }
         $attribute_is_taxonomy = $_POST['attribute_is_taxonomy'];
         $attribute_position = $_POST['attribute_position'];
         $attribute_names_max_key = max(array_keys($attribute_names));
         for ($i = 0; $i <= $attribute_names_max_key; $i++) {
             if (empty($attribute_names[$i])) {
                 continue;
             }
             $is_visible = isset($attribute_visibility[$i]) ? 1 : 0;
             $is_variation = isset($attribute_variation[$i]) ? 1 : 0;
             $is_taxonomy = $attribute_is_taxonomy[$i] ? 1 : 0;
             if ($is_taxonomy) {
                 $values_are_slugs = false;
                 if (isset($attribute_values[$i])) {
                     // Select based attributes - Format values (posted values are slugs)
                     if (is_array($attribute_values[$i])) {
                         $values = array_map('sanitize_title', $attribute_values[$i]);
                         $values_are_slugs = true;
                         // Text based attributes - Posted values are term names - don't change to slugs
                     } else {
                         $values = array_map('stripslashes', array_map('strip_tags', explode(WC_DELIMITER, $attribute_values[$i])));
                     }
                     // Remove empty items in the array
                     $values = array_filter($values, 'strlen');
                 } else {
                     $values = array();
                 }
                 // Update post terms
                 if (taxonomy_exists($attribute_names[$i])) {
                     foreach ($values as $key => $value) {
                         $term = get_term_by($values_are_slugs ? 'slug' : 'name', trim($value), $attribute_names[$i]);
                         if ($term) {
                             $values[$key] = intval($term->term_id);
                         } else {
                             $term = wp_insert_term(trim($value), $attribute_names[$i]);
                             if (isset($term->term_id)) {
                                 $values[$key] = intval($term->term_id);
                             }
                         }
                     }
                     wp_set_object_terms($post_id, $values, $attribute_names[$i]);
                 }
                 if (!empty($values)) {
                     // Add attribute to array, but don't set values
                     $attributes[sanitize_title($attribute_names[$i])] = array('name' => wc_clean($attribute_names[$i]), 'value' => '', 'position' => $attribute_position[$i], 'is_visible' => $is_visible, 'is_variation' => $is_variation, 'is_taxonomy' => $is_taxonomy);
                 }
             } elseif (isset($attribute_values[$i])) {
                 // Text based, possibly separated by pipes (WC_DELIMITER). Preserve line breaks in non-variation attributes.
                 $values = $is_variation ? wc_clean($attribute_values[$i]) : implode("\n", array_map('wc_clean', explode("\n", $attribute_values[$i])));
                 $values = implode(' ' . WC_DELIMITER . ' ', wc_get_text_attributes($values));
                 // Custom attribute - Add attribute to array and set the values
                 $attributes[sanitize_title($attribute_names[$i])] = array('name' => wc_clean($attribute_names[$i]), 'value' => $values, 'position' => $attribute_position[$i], 'is_visible' => $is_visible, 'is_variation' => $is_variation, 'is_taxonomy' => $is_taxonomy);
             }
         }
     }
     uasort($attributes, 'wc_product_attribute_uasort_comparison');
     /**
      * Unset removed attributes by looping over previous values and
      * unsetting the terms.
      */
     $old_attributes = array_filter((array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true)));
     if (!empty($old_attributes)) {
         foreach ($old_attributes as $key => $value) {
             if (empty($attributes[$key]) && !empty($value['is_taxonomy']) && taxonomy_exists($key)) {
                 wp_set_object_terms($post_id, array(), $key);
             }
         }
     }
     /**
      * After removed attributes are unset, we can set the new attribute data.
      */
     update_post_meta($post_id, '_product_attributes', $attributes);
     // Sales and prices
     if (in_array($product_type, array('variable', 'grouped'))) {
         // Variable and grouped products have no prices
         update_post_meta($post_id, '_regular_price', '');
         update_post_meta($post_id, '_sale_price', '');
         update_post_meta($post_id, '_sale_price_dates_from', '');
         update_post_meta($post_id, '_sale_price_dates_to', '');
     } else {
         $date_from = (string) isset($_POST['_sale_price_dates_from']) ? wc_clean($_POST['_sale_price_dates_from']) : '';
         $date_to = (string) isset($_POST['_sale_price_dates_to']) ? wc_clean($_POST['_sale_price_dates_to']) : '';
         $regular_price = (string) isset($_POST['_regular_price']) ? wc_clean($_POST['_regular_price']) : '';
         $sale_price = (string) isset($_POST['_sale_price']) ? wc_clean($_POST['_sale_price']) : '';
         update_post_meta($post_id, '_regular_price', '' === $regular_price ? '' : wc_format_decimal($regular_price));
         update_post_meta($post_id, '_sale_price', '' === $sale_price ? '' : wc_format_decimal($sale_price));
         // Dates
         update_post_meta($post_id, '_sale_price_dates_from', $date_from ? strtotime($date_from) : '');
         update_post_meta($post_id, '_sale_price_dates_to', $date_to ? strtotime($date_to) : '');
         if ($date_to && !$date_from) {
             $date_from = date('Y-m-d');
             update_post_meta($post_id, '_sale_price_dates_from', strtotime($date_from));
         }
         // Update price if on sale
         if ('' !== $sale_price && '' === $date_to && '' === $date_from) {
             update_post_meta($post_id, '_price', wc_format_decimal($sale_price));
         } elseif ('' !== $sale_price && $date_from && strtotime($date_from) <= strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($post_id, '_price', wc_format_decimal($sale_price));
         } else {
             update_post_meta($post_id, '_price', '' === $regular_price ? '' : wc_format_decimal($regular_price));
         }
         if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
             update_post_meta($post_id, '_price', '' === $regular_price ? '' : wc_format_decimal($regular_price));
             update_post_meta($post_id, '_sale_price', '');
             update_post_meta($post_id, '_sale_price_dates_from', '');
             update_post_meta($post_id, '_sale_price_dates_to', '');
         }
     }
     // Update parent if grouped so price sorting works and stays in sync with the cheapest child
     if ($post->post_parent > 0 || 'grouped' === $product_type || $_POST['previous_parent_id'] > 0) {
         $clear_parent_ids = array();
         if ($post->post_parent > 0) {
             $clear_parent_ids[] = $post->post_parent;
         }
         if ('grouped' === $product_type) {
             $clear_parent_ids[] = $post_id;
         }
         if ($_POST['previous_parent_id'] > 0) {
             $clear_parent_ids[] = absint($_POST['previous_parent_id']);
         }
         if (!empty($clear_parent_ids)) {
             foreach ($clear_parent_ids as $clear_id) {
                 $children_by_price = get_posts(array('post_parent' => $clear_id, 'orderby' => 'meta_value_num', 'order' => 'asc', 'meta_key' => '_price', 'posts_per_page' => 1, 'post_type' => 'product', 'fields' => 'ids'));
                 if ($children_by_price) {
                     foreach ($children_by_price as $child) {
                         $child_price = get_post_meta($child, '_price', true);
                         update_post_meta($clear_id, '_price', $child_price);
                     }
                 }
                 wc_delete_product_transients($clear_id);
             }
         }
     }
     // Sold Individually
     if (!empty($_POST['_sold_individually'])) {
         update_post_meta($post_id, '_sold_individually', 'yes');
     } else {
         update_post_meta($post_id, '_sold_individually', '');
     }
     // Stock Data
     if ('yes' === get_option('woocommerce_manage_stock')) {
         $manage_stock = 'no';
         $backorders = 'no';
         $stock_status = wc_clean($_POST['_stock_status']);
         if ('external' === $product_type) {
             $stock_status = 'instock';
         } elseif ('variable' === $product_type) {
             // Stock status is always determined by children so sync later
             $stock_status = '';
             if (!empty($_POST['_manage_stock'])) {
                 $manage_stock = 'yes';
                 $backorders = wc_clean($_POST['_backorders']);
             }
         } elseif ('grouped' !== $product_type && !empty($_POST['_manage_stock'])) {
             $manage_stock = 'yes';
             $backorders = wc_clean($_POST['_backorders']);
         }
         update_post_meta($post_id, '_manage_stock', $manage_stock);
         update_post_meta($post_id, '_backorders', $backorders);
         if ($stock_status) {
             wc_update_product_stock_status($post_id, $stock_status);
         }
         if (!empty($_POST['_manage_stock'])) {
             wc_update_product_stock($post_id, wc_stock_amount($_POST['_stock']));
         } else {
             update_post_meta($post_id, '_stock', '');
         }
     } elseif ('variable' !== $product_type) {
         wc_update_product_stock_status($post_id, wc_clean($_POST['_stock_status']));
     }
     // Cross sells and upsells
     $upsells = isset($_POST['upsell_ids']) ? array_filter(array_map('intval', explode(',', $_POST['upsell_ids']))) : array();
     $crosssells = isset($_POST['crosssell_ids']) ? array_filter(array_map('intval', explode(',', $_POST['crosssell_ids']))) : array();
     update_post_meta($post_id, '_upsell_ids', $upsells);
     update_post_meta($post_id, '_crosssell_ids', $crosssells);
     // Downloadable options
     if ('yes' == $is_downloadable) {
         $_download_limit = absint($_POST['_download_limit']);
         if (!$_download_limit) {
             $_download_limit = '';
             // 0 or blank = unlimited
         }
         $_download_expiry = absint($_POST['_download_expiry']);
         if (!$_download_expiry) {
             $_download_expiry = '';
             // 0 or blank = unlimited
         }
         // file paths will be stored in an array keyed off md5(file path)
         $files = array();
         if (isset($_POST['_wc_file_urls'])) {
             $file_names = isset($_POST['_wc_file_names']) ? $_POST['_wc_file_names'] : array();
             $file_urls = isset($_POST['_wc_file_urls']) ? wp_unslash(array_map('trim', $_POST['_wc_file_urls'])) : array();
             $file_url_size = sizeof($file_urls);
             $allowed_file_types = apply_filters('woocommerce_downloadable_file_allowed_mime_types', get_allowed_mime_types());
             for ($i = 0; $i < $file_url_size; $i++) {
                 if (!empty($file_urls[$i])) {
                     // Find type and file URL
                     if (0 === strpos($file_urls[$i], 'http')) {
                         $file_is = 'absolute';
                         $file_url = esc_url_raw($file_urls[$i]);
                     } elseif ('[' === substr($file_urls[$i], 0, 1) && ']' === substr($file_urls[$i], -1)) {
                         $file_is = 'shortcode';
                         $file_url = wc_clean($file_urls[$i]);
                     } else {
                         $file_is = 'relative';
                         $file_url = wc_clean($file_urls[$i]);
                     }
                     $file_name = wc_clean($file_names[$i]);
                     $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, '?'), $allowed_file_types);
                         $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) {
                         $_file_url = $file_url;
                         if ('..' === substr($file_url, 0, 2) || '/' !== substr($file_url, 0, 1)) {
                             $_file_url = realpath(ABSPATH . $file_url);
                         }
                         if (!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, 0, $files);
         update_post_meta($post_id, '_downloadable_files', $files);
         update_post_meta($post_id, '_download_limit', $_download_limit);
         update_post_meta($post_id, '_download_expiry', $_download_expiry);
         if (isset($_POST['_download_type'])) {
             update_post_meta($post_id, '_download_type', wc_clean($_POST['_download_type']));
         }
     }
     // Product url
     if ('external' == $product_type) {
         if (isset($_POST['_product_url'])) {
             update_post_meta($post_id, '_product_url', esc_url_raw($_POST['_product_url']));
         }
         if (isset($_POST['_button_text'])) {
             update_post_meta($post_id, '_button_text', wc_clean($_POST['_button_text']));
         }
     }
     // Save variations
     if ('variable' == $product_type) {
         // Update parent if variable so price sorting works and stays in sync with the cheapest child
         WC_Product_Variable::sync($post_id);
         WC_Product_Variable::sync_stock_status($post_id);
     }
     // Update version after saving
     update_post_meta($post_id, '_product_version', WC_VERSION);
     // Do action for product type
     do_action('woocommerce_process_product_meta_' . $product_type, $post_id);
     // Clear cache/transients
     wc_delete_product_transients($post_id);
 }
 /**
  * set_stock_status function.
  */
 public function set_stock_status($status)
 {
     $status = 'outofstock' === $status ? 'outofstock' : 'instock';
     // Sanity check
     if (true === $this->managing_stock()) {
         if (!$this->backorders_allowed() && $this->get_stock_quantity() <= get_option('woocommerce_notify_no_stock_amount')) {
             $status = 'outofstock';
         }
     } elseif ('parent' === $this->managing_stock()) {
         if (!$this->parent->backorders_allowed() && $this->parent->get_stock_quantity() <= get_option('woocommerce_notify_no_stock_amount')) {
             $status = 'outofstock';
         }
     }
     if (update_post_meta($this->variation_id, '_stock_status', $status)) {
         do_action('woocommerce_variation_set_stock_status', $this->variation_id, $status);
         if (true === $this->managing_stock()) {
             WC_Product_Variable::sync_stock_status($this->id);
         }
     }
 }
 /**
  * Edit a product
  *
  * @since 2.2
  * @param int $id the product ID
  * @param array $data
  * @return array
  */
 public function edit_product($id, $data)
 {
     try {
         if (!isset($data['product'])) {
             throw new WC_API_Exception('woocommerce_api_missing_product_data', sprintf(__('No %1$s data specified to edit %1$s', 'woocommerce'), 'product'), 400);
         }
         $data = $data['product'];
         $id = $this->validate_request($id, 'product', 'edit');
         if (is_wp_error($id)) {
             return $id;
         }
         $data = apply_filters('woocommerce_api_edit_product_data', $data, $this);
         // Product title.
         if (isset($data['title'])) {
             wp_update_post(array('ID' => $id, 'post_title' => wc_clean($data['title'])));
         }
         // Product name (slug).
         if (isset($data['name'])) {
             wp_update_post(array('ID' => $id, 'post_name' => sanitize_title($data['name'])));
         }
         // Product status.
         if (isset($data['status'])) {
             wp_update_post(array('ID' => $id, 'post_status' => wc_clean($data['status'])));
         }
         // Product short description.
         if (isset($data['short_description'])) {
             // Enable short description html tags.
             $post_excerpt = isset($data['enable_html_short_description']) && true === $data['enable_html_short_description'] ? $data['short_description'] : wc_clean($data['short_description']);
             wp_update_post(array('ID' => $id, 'post_excerpt' => $post_excerpt));
         }
         // Product description.
         if (isset($data['description'])) {
             // Enable description html tags.
             $post_content = isset($data['enable_html_description']) && true === $data['enable_html_description'] ? $data['description'] : wc_clean($data['description']);
             wp_update_post(array('ID' => $id, 'post_content' => $post_content));
         }
         // Menu order.
         if (isset($data['menu_order'])) {
             wp_update_post(array('ID' => $id, 'menu_order' => intval($data['menu_order'])));
         }
         // Validate the product type.
         if (isset($data['type']) && !in_array(wc_clean($data['type']), array_keys(wc_get_product_types()))) {
             throw new WC_API_Exception('woocommerce_api_invalid_product_type', sprintf(__('Invalid product type - the product type must be any of these: %s', 'woocommerce'), implode(', ', array_keys(wc_get_product_types()))), 400);
         }
         // Check for featured/gallery images, upload it and set it.
         if (isset($data['images'])) {
             $this->save_product_images($id, $data['images']);
         }
         // Save product meta fields.
         $this->save_product_meta($id, $data);
         // Save variations.
         $product = get_product($id);
         if ($product->is_type('variable')) {
             if (isset($data['variations']) && is_array($data['variations'])) {
                 $this->save_variations($id, $data);
             } else {
                 // Just sync variations
                 WC_Product_Variable::sync($id);
                 WC_Product_Variable::sync_stock_status($id);
             }
         }
         do_action('woocommerce_api_edit_product', $id, $data);
         // Clear cache/transients.
         wc_delete_product_transients($id);
         return $this->get_product($id);
     } catch (WC_API_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }
Ejemplo n.º 5
0
 public function fixVariableStockStatus()
 {
     // get all parent variations
     $args = array('post_type' => 'product', 'posts_per_page' => -1, 'tax_query' => array(array('taxonomy' => 'product_type', 'field' => 'slug', 'terms' => array('variable'))));
     $query = new WP_Query($args);
     $parent_variations = $query->posts;
     // loop products
     foreach ($parent_variations as $post) {
         // $this->fixVariableStockStatusForProduct( $post->ID );
         WC_Product_Variable::sync_stock_status($post->ID);
     }
 }
 /**
  * Update post meta fields.
  *
  * @param WP_Post $post
  * @param WP_REST_Request $request
  * @return bool|WP_Error
  */
 protected function update_post_meta_fields($post, $request)
 {
     try {
         $product = wc_get_product($post);
         // Check for featured/gallery images, upload it and set it.
         if (isset($request['images'])) {
             $this->save_product_images($product->id, $request['images']);
         }
         // Save product meta fields.
         $this->save_product_meta($product, $request);
         // Save variations.
         if ($product->is_type('variable')) {
             if (isset($request['variations']) && is_array($request['variations'])) {
                 $this->save_variations_data($product, $request);
             } else {
                 // Just sync variations.
                 WC_Product_Variable::sync($product->id);
                 WC_Product_Variable::sync_stock_status($product->id);
             }
         }
         return true;
     } catch (WC_REST_Exception $e) {
         return new WP_Error($e->getErrorCode(), $e->getMessage(), array('status' => $e->getCode()));
     }
 }