function sf_single_variation_add_to_cart_button() { global $product; $loading_text = __('Adding...', 'swiftframework'); $added_text = __('Item added', 'swiftframework'); ?> <div class="variations_button"> <?php woocommerce_quantity_input(array('input_value' => isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1)); ?> <button type="submit" data-product_id="<?php echo esc_attr($product->id); ?> " data-quantity="1" data-default_text="<?php echo esc_attr($product->single_add_to_cart_text()); ?> " data-default_icon="sf-icon-add-to-cart" data-loading_text="<?php echo esc_attr($loading_text); ?> " data-added_text="<?php echo esc_attr($added_text); ?> " class="single_add_to_cart_button button alt"><?php echo apply_filters('sf_add_to_cart_icon', '<i class="sf-icon-add-to-cart"></i>'); ?> <span><?php echo esc_attr($product->single_add_to_cart_text()); ?> </span></button> <input type="hidden" name="add-to-cart" value="<?php echo absint($product->id); ?> " /> <input type="hidden" name="product_id" value="<?php echo absint($product->id); ?> " /> <input type="hidden" name="variation_id" class="variation_id" value="" /> <?php echo sf_wishlist_button(); ?> </div> <?php }
<?php do_action('woocommerce_before_add_to_cart_button'); ?> <div class="single_variation_wrap" style="display:none;"> <?php do_action('woocommerce_before_single_variation'); ?> <div class="single_variation"></div> <div class="variations_button"> <?php woocommerce_quantity_input(array('input_value' => isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1)); ?> <button type="submit" class="single_add_to_cart_button button alt"><?php echo $product->single_add_to_cart_text(); ?> </button> </div> <input type="hidden" name="add-to-cart" value="<?php echo absint($product->id); ?> " /> <input type="hidden" name="product_id" value="<?php echo absint($product->id); ?> " />
/** * @param $product */ function hwoo_simple_product_quantity_input($product) { if ($product instanceof HWoo_TimberProduct) { $product = $product->wc_product(); } if (!$product->is_sold_individually()) { woocommerce_quantity_input(array('min_value' => apply_filters('woocommerce_quantity_input_min', 1, $product), 'max_value' => apply_filters('woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product), 'input_value' => isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1)); } }
/** * Show input qty on single product * @return write */ function show_select_qty_btn_single() { global $product; $qty = isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1; if (!$product->is_sold_individually()) { echo '<div class="buttons-qty">'; echo '<span>+</span>'; echo '<input class="single-product" data-id="' . $product->id . '" type="text" value="' . $qty . '" />'; echo '<span>-</span>'; echo '</div>'; } }
/** * Output a text input box. * * @param array $field */ function woocommerce_wp_text_input($field) { global $thepostid, $post; $thepostid = empty($thepostid) ? $post->ID : $thepostid; $field['placeholder'] = isset($field['placeholder']) ? $field['placeholder'] : ''; $field['class'] = isset($field['class']) ? $field['class'] : 'short'; $field['style'] = isset($field['style']) ? $field['style'] : ''; $field['wrapper_class'] = isset($field['wrapper_class']) ? $field['wrapper_class'] : ''; $field['value'] = isset($field['value']) ? $field['value'] : get_post_meta($thepostid, $field['id'], true); $field['name'] = isset($field['name']) ? $field['name'] : $field['id']; $field['type'] = isset($field['type']) ? $field['type'] : 'text'; $field['desc_tip'] = isset($field['desc_tip']) ? $field['desc_tip'] : false; $data_type = empty($field['data_type']) ? '' : $field['data_type']; switch ($data_type) { case 'price': $field['class'] .= ' wc_input_price'; $field['value'] = wc_format_localized_price($field['value']); break; case 'decimal': $field['class'] .= ' wc_input_decimal'; $field['value'] = wc_format_localized_decimal($field['value']); break; case 'stock': $field['class'] .= ' wc_input_stock'; $field['value'] = wc_stock_amount($field['value']); break; case 'url': $field['class'] .= ' wc_input_url'; $field['value'] = esc_url($field['value']); break; default: break; } // Custom attribute handling $custom_attributes = array(); if (!empty($field['custom_attributes']) && is_array($field['custom_attributes'])) { foreach ($field['custom_attributes'] as $attribute => $value) { $custom_attributes[] = esc_attr($attribute) . '="' . esc_attr($value) . '"'; } } echo '<p class="form-field ' . esc_attr($field['id']) . '_field ' . esc_attr($field['wrapper_class']) . '"> <label for="' . esc_attr($field['id']) . '">' . wp_kses_post($field['label']) . '</label>'; if (!empty($field['description']) && false !== $field['desc_tip']) { echo wc_help_tip($field['description']); } echo '<input type="' . esc_attr($field['type']) . '" class="' . esc_attr($field['class']) . '" style="' . esc_attr($field['style']) . '" name="' . esc_attr($field['name']) . '" id="' . esc_attr($field['id']) . '" value="' . esc_attr($field['value']) . '" placeholder="' . esc_attr($field['placeholder']) . '" ' . implode(' ', $custom_attributes) . ' /> '; if (!empty($field['description']) && false === $field['desc_tip']) { echo '<span class="description">' . wp_kses_post($field['description']) . '</span>'; } echo '</p>'; }
/** * Get total stock. * * This is the stock of parent and children combined. * * @access public * @return int */ public function get_total_stock() { if (empty($this->total_stock)) { $transient_name = 'wc_product_total_stock_' . $this->id . WC_Cache_Helper::get_transient_version('product'); if (false === ($this->total_stock = get_transient($transient_name))) { $this->total_stock = max(0, wc_stock_amount($this->stock)); if (sizeof($this->get_children()) > 0) { foreach ($this->get_children() as $child_id) { if ('yes' === get_post_meta($child_id, '_manage_stock', true)) { $stock = get_post_meta($child_id, '_stock', true); $this->total_stock += max(0, wc_stock_amount($stock)); } } } set_transient($transient_name, $this->total_stock, DAY_IN_SECONDS * 30); } } return wc_stock_amount($this->total_stock); }
/** * Get total stock. * * This is the stock of parent and children combined. * * @access public * @return int */ public function get_total_stock() { if (empty($this->total_stock)) { $transient_name = 'wc_product_total_stock_' . $this->id; if (false === ($this->total_stock = get_transient($transient_name))) { $this->total_stock = $this->stock; if (sizeof($this->get_children()) > 0) { foreach ($this->get_children() as $child_id) { $stock = get_post_meta($child_id, '_stock', true); if ($stock != '') { $this->total_stock += wc_stock_amount($stock); } } } set_transient($transient_name, $this->total_stock, YEAR_IN_SECONDS); } } return wc_stock_amount($this->total_stock); }
/** * Get sales reports. * * @param WP_REST_Request $request * @return array|WP_Error */ public function get_items($request) { // Set date filtering. $filter = array('period' => $request['period'], 'date_min' => $request['date_min'], 'date_max' => $request['date_max']); $this->setup_report($filter); $report_data = $this->report->get_order_report_data(array('data' => array('_product_id' => array('type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => '', 'name' => 'product_id'), '_qty' => array('type' => 'order_item_meta', 'order_item_type' => 'line_item', 'function' => 'SUM', 'name' => 'order_item_qty')), 'order_by' => 'order_item_qty DESC', 'group_by' => 'product_id', 'limit' => isset($filter['limit']) ? absint($filter['limit']) : 12, 'query_type' => 'get_results', 'filter_range' => true)); $top_sellers = array(); foreach ($report_data as $item) { $product = wc_get_product($item->product_id); if ($product) { $top_sellers[] = array('name' => $product->get_title(), 'product_id' => (int) $item->product_id, 'quantity' => wc_stock_amount($item->order_item_qty)); } } $data = array(); foreach ($top_sellers as $top_seller) { $item = $this->prepare_item_for_response((object) $top_seller, $request); $data[] = $this->prepare_response_for_collection($item); } return rest_ensure_response($data); }
/** * Override the Output the add to cart button for variations. */ function woocommerce_single_variation_add_to_cart_button() { global $product; ?> <div class="variations_button"> <button type="submit" class="single_add_to_cart_button button alt"><?php echo esc_html($product->single_add_to_cart_text()); ?> </button> <input type="hidden" name="add-to-cart" value="<?php echo absint($product->id); ?> " /> <input type="hidden" name="product_id" value="<?php echo absint($product->id); ?> " /> <input type="hidden" name="variation_id" class="variation_id" value="" /> <?php woocommerce_quantity_input(array('input_value' => isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1)); ?> </div> <?php }
/** * Save variations. * * @throws WC_REST_Exception REST API exceptions. * @param WC_Product $product Product instance. * @param WP_REST_Request $request Request data. * @param bool $single_variation True if saving only a single variation. * @return bool */ protected function save_variations_data($product, $request, $single_variation = false) { global $wpdb; if ($single_variation) { $variations = array($request); } else { $variations = $request['variations']; } foreach ($variations as $menu_order => $data) { $variation_id = isset($data['id']) ? absint($data['id']) : 0; $variation = new WC_Product_Variation($variation_id); // Create initial name and status. if (!$variation->get_slug()) { /* translators: 1: variation id 2: product name */ $variation->set_name(sprintf(__('Variation #%1$s of %2$s', 'woocommerce'), $variation->get_id(), $product->get_name())); $variation->set_status(isset($data['visible']) && false === $data['visible'] ? 'private' : 'publish'); } // Parent ID. $variation->set_parent_id($product->get_id()); // Menu order. $variation->set_menu_order($menu_order); // Status. if (isset($data['visible'])) { $variation->set_status(false === $data['visible'] ? 'private' : 'publish'); } // SKU. if (isset($data['sku'])) { $variation->set_sku(wc_clean($data['sku'])); } // Thumbnail. if (isset($data['image']) && is_array($data['image'])) { $image = $data['image']; $image = current($image); if (is_array($image)) { $image['position'] = 0; } $variation = $this->save_product_images($variation, array($image)); } // Virtual variation. if (isset($data['virtual'])) { $variation->set_virtual($data['virtual']); } // Downloadable variation. if (isset($data['downloadable'])) { $variation->set_downloadable($data['downloadable']); } // Downloads. if ($variation->get_downloadable()) { // Downloadable files. if (isset($data['downloads']) && is_array($data['downloads'])) { $variation = $this->save_downloadable_files($variation, $data['downloads']); } // Download limit. if (isset($data['download_limit'])) { $variation->set_download_limit($data['download_limit']); } // Download expiry. if (isset($data['download_expiry'])) { $variation->set_download_expiry($data['download_expiry']); } } // Shipping data. $variation = $this->save_product_shipping_data($variation, $data); // Stock handling. if (isset($data['manage_stock'])) { $variation->set_manage_stock($data['manage_stock']); } if (isset($data['in_stock'])) { $variation->set_stock_status(true === $data['in_stock'] ? 'instock' : 'outofstock'); } if (isset($data['backorders'])) { $variation->set_backorders($data['backorders']); } if ($variation->get_manage_stock()) { if (isset($data['stock_quantity'])) { $variation->set_stock_quantity($data['stock_quantity']); } elseif (isset($data['inventory_delta'])) { $stock_quantity = wc_stock_amount($variation->get_stock_amount()); $stock_quantity += wc_stock_amount($data['inventory_delta']); $variation->set_stock_quantity($stock_quantity); } } else { $variation->set_backorders('no'); $variation->set_stock_quantity(''); } // Regular Price. if (isset($data['regular_price'])) { $variation->set_regular_price($data['regular_price']); } // Sale Price. if (isset($data['sale_price'])) { $variation->set_sale_price($data['sale_price']); } if (isset($data['date_on_sale_from'])) { $variation->set_date_on_sale_from($data['date_on_sale_from']); } if (isset($data['date_on_sale_to'])) { $variation->set_date_on_sale_to($data['date_on_sale_to']); } // Tax class. if (isset($data['tax_class'])) { $variation->set_tax_class($data['tax_class']); } // Description. if (isset($data['description'])) { $variation->set_description(wp_kses_post($data['description'])); } // Update taxonomies. if (isset($data['attributes'])) { $attributes = array(); $parent_attributes = $product->get_attributes(); foreach ($data['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($parent_attributes[$attribute_name]) || !$parent_attributes[$attribute_name]->get_variation()) { continue; } $attribute_key = sanitize_title($parent_attributes[$attribute_name]->get_name()); $attribute_value = isset($attribute['option']) ? wc_clean(stripslashes($attribute['option'])) : ''; if ($parent_attributes[$attribute_name]->is_taxonomy()) { // If dealing with a taxonomy, we need to get the slug from the name posted to the API. $term = get_term_by('name', $attribute_value, $attribute_name); if ($term && !is_wp_error($term)) { $attribute_value = $term->slug; } else { $attribute_value = sanitize_title($attribute_value); } } $attributes[$attribute_key] = $attribute_value; } $variation->set_attributes($attributes); } $variation->save(); do_action('woocommerce_rest_save_product_variation', $variation->get_id(), $menu_order, $data); } return true; }
/** * Save meta box data * * @deprecated 2.4.0 Deprecated in favor to WC_AJAX::save_variations() */ public static function save_variations($post_id, $post) { global $wpdb; $attributes = (array) maybe_unserialize(get_post_meta($post_id, '_product_attributes', true)); if (isset($_POST['variable_sku'])) { $variable_post_id = $_POST['variable_post_id']; $variable_sku = $_POST['variable_sku']; $variable_regular_price = $_POST['variable_regular_price']; $variable_sale_price = $_POST['variable_sale_price']; $upload_image_id = $_POST['upload_image_id']; $variable_download_limit = $_POST['variable_download_limit']; $variable_download_expiry = $_POST['variable_download_expiry']; $variable_shipping_class = $_POST['variable_shipping_class']; $variable_tax_class = isset($_POST['variable_tax_class']) ? $_POST['variable_tax_class'] : array(); $variable_menu_order = $_POST['variation_menu_order']; $variable_sale_price_dates_from = $_POST['variable_sale_price_dates_from']; $variable_sale_price_dates_to = $_POST['variable_sale_price_dates_to']; $variable_weight = isset($_POST['variable_weight']) ? $_POST['variable_weight'] : array(); $variable_length = isset($_POST['variable_length']) ? $_POST['variable_length'] : array(); $variable_width = isset($_POST['variable_width']) ? $_POST['variable_width'] : array(); $variable_height = isset($_POST['variable_height']) ? $_POST['variable_height'] : array(); $variable_enabled = isset($_POST['variable_enabled']) ? $_POST['variable_enabled'] : array(); $variable_is_virtual = isset($_POST['variable_is_virtual']) ? $_POST['variable_is_virtual'] : array(); $variable_is_downloadable = isset($_POST['variable_is_downloadable']) ? $_POST['variable_is_downloadable'] : array(); $variable_manage_stock = isset($_POST['variable_manage_stock']) ? $_POST['variable_manage_stock'] : array(); $variable_stock = isset($_POST['variable_stock']) ? $_POST['variable_stock'] : array(); $variable_backorders = isset($_POST['variable_backorders']) ? $_POST['variable_backorders'] : array(); $variable_stock_status = isset($_POST['variable_stock_status']) ? $_POST['variable_stock_status'] : array(); $variable_description = isset($_POST['variable_description']) ? $_POST['variable_description'] : array(); $max_loop = max(array_keys($_POST['variable_post_id'])); for ($i = 0; $i <= $max_loop; $i++) { if (!isset($variable_post_id[$i])) { continue; } $variation_id = absint($variable_post_id[$i]); // Checkboxes $is_virtual = isset($variable_is_virtual[$i]) ? 'yes' : 'no'; $is_downloadable = isset($variable_is_downloadable[$i]) ? 'yes' : 'no'; $post_status = isset($variable_enabled[$i]) ? 'publish' : 'private'; $manage_stock = isset($variable_manage_stock[$i]) ? 'yes' : 'no'; // Generate a useful post title $variation_post_title = sprintf(__('Variation #%s of %s', 'woocommerce'), absint($variation_id), esc_html(get_the_title($post_id))); // Update or Add post if (!$variation_id) { $variation = array('post_title' => $variation_post_title, 'post_content' => '', 'post_status' => $post_status, 'post_author' => get_current_user_id(), 'post_parent' => $post_id, 'post_type' => 'product_variation', 'menu_order' => $variable_menu_order[$i]); $variation_id = wp_insert_post($variation); do_action('woocommerce_create_product_variation', $variation_id); } else { $wpdb->update($wpdb->posts, array('post_status' => $post_status, 'post_title' => $variation_post_title, 'menu_order' => $variable_menu_order[$i]), array('ID' => $variation_id)); do_action('woocommerce_update_product_variation', $variation_id); } // Only continue if we have a variation ID if (!$variation_id) { continue; } // Unique SKU $sku = get_post_meta($variation_id, '_sku', true); $new_sku = wc_clean(stripslashes($variable_sku[$i])); if ('' == $new_sku) { update_post_meta($variation_id, '_sku', ''); } elseif ($new_sku !== $sku) { if (!empty($new_sku)) { $unique_sku = wc_product_has_unique_sku($variation_id, $new_sku); if (!$unique_sku) { WC_Admin_Meta_Boxes::add_error(__('Variation SKU must be unique.', 'woocommerce')); } else { update_post_meta($variation_id, '_sku', $new_sku); } } else { update_post_meta($variation_id, '_sku', ''); } } // Update post meta update_post_meta($variation_id, '_thumbnail_id', absint($upload_image_id[$i])); update_post_meta($variation_id, '_virtual', wc_clean($is_virtual)); update_post_meta($variation_id, '_downloadable', wc_clean($is_downloadable)); if (isset($variable_weight[$i])) { update_post_meta($variation_id, '_weight', '' === $variable_weight[$i] ? '' : wc_format_decimal($variable_weight[$i])); } if (isset($variable_length[$i])) { update_post_meta($variation_id, '_length', '' === $variable_length[$i] ? '' : wc_format_decimal($variable_length[$i])); } if (isset($variable_width[$i])) { update_post_meta($variation_id, '_width', '' === $variable_width[$i] ? '' : wc_format_decimal($variable_width[$i])); } if (isset($variable_height[$i])) { update_post_meta($variation_id, '_height', '' === $variable_height[$i] ? '' : wc_format_decimal($variable_height[$i])); } // Stock handling update_post_meta($variation_id, '_manage_stock', $manage_stock); // Only update stock status to user setting if changed by the user, but do so before looking at stock levels at variation level if (!empty($variable_stock_status[$i])) { wc_update_product_stock_status($variation_id, $variable_stock_status[$i]); } if ('yes' === $manage_stock) { update_post_meta($variation_id, '_backorders', wc_clean($variable_backorders[$i])); wc_update_product_stock($variation_id, wc_stock_amount($variable_stock[$i])); } else { delete_post_meta($variation_id, '_backorders'); delete_post_meta($variation_id, '_stock'); } // Price handling $regular_price = wc_format_decimal($variable_regular_price[$i]); $sale_price = $variable_sale_price[$i] === '' ? '' : wc_format_decimal($variable_sale_price[$i]); $date_from = wc_clean($variable_sale_price_dates_from[$i]); $date_to = wc_clean($variable_sale_price_dates_to[$i]); update_post_meta($variation_id, '_regular_price', $regular_price); update_post_meta($variation_id, '_sale_price', $sale_price); // Save Dates update_post_meta($variation_id, '_sale_price_dates_from', $date_from ? strtotime($date_from) : ''); update_post_meta($variation_id, '_sale_price_dates_to', $date_to ? strtotime($date_to) : ''); if ($date_to && !$date_from) { update_post_meta($variation_id, '_sale_price_dates_from', strtotime('NOW', current_time('timestamp'))); } // Update price if on sale if ('' !== $sale_price && '' === $date_to && '' === $date_from) { update_post_meta($variation_id, '_price', $sale_price); } else { update_post_meta($variation_id, '_price', $regular_price); } if ('' !== $sale_price && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) { update_post_meta($variation_id, '_price', $sale_price); } if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) { update_post_meta($variation_id, '_price', $regular_price); update_post_meta($variation_id, '_sale_price_dates_from', ''); update_post_meta($variation_id, '_sale_price_dates_to', ''); } if (isset($variable_tax_class[$i]) && $variable_tax_class[$i] !== 'parent') { update_post_meta($variation_id, '_tax_class', wc_clean($variable_tax_class[$i])); } else { delete_post_meta($variation_id, '_tax_class'); } if ('yes' == $is_downloadable) { update_post_meta($variation_id, '_download_limit', wc_clean($variable_download_limit[$i])); update_post_meta($variation_id, '_download_expiry', wc_clean($variable_download_expiry[$i])); $files = array(); $file_names = isset($_POST['_wc_variation_file_names'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_names'][$variation_id]) : array(); $file_urls = isset($_POST['_wc_variation_file_urls'][$variation_id]) ? array_map('wc_clean', $_POST['_wc_variation_file_urls'][$variation_id]) : array(); $file_url_size = sizeof($file_urls); $allowed_file_types = get_allowed_mime_types(); for ($ii = 0; $ii < $file_url_size; $ii++) { if (!empty($file_urls[$ii])) { // Find type and file URL if (0 === strpos($file_urls[$ii], 'http')) { $file_is = 'absolute'; $file_url = esc_url_raw($file_urls[$ii]); } elseif ('[' === substr($file_urls[$ii], 0, 1) && ']' === substr($file_urls[$ii], -1)) { $file_is = 'shortcode'; $file_url = wc_clean($file_urls[$ii]); } else { $file_is = 'relative'; $file_url = wc_clean($file_urls[$ii]); } $file_name = wc_clean($file_names[$ii]); $file_hash = md5($file_url); // Validate the file extension if (in_array($file_is, array('absolute', 'relative'))) { $file_type = wp_check_filetype(strtok($file_url, '?')); $parsed_url = parse_url($file_url, PHP_URL_PATH); $extension = pathinfo($parsed_url, PATHINFO_EXTENSION); if (!empty($extension) && !in_array($file_type['type'], $allowed_file_types)) { WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not have an allowed file type. Allowed types include: %s', 'woocommerce'), '<code>' . basename($file_url) . '</code>', '<code>' . implode(', ', array_keys($allowed_file_types)) . '</code>')); continue; } } // Validate the file exists if ('relative' === $file_is && !apply_filters('woocommerce_downloadable_file_exists', file_exists($file_url), $file_url)) { WC_Admin_Meta_Boxes::add_error(sprintf(__('The downloadable file %s cannot be used as it does not exist on the server.', 'woocommerce'), '<code>' . $file_url . '</code>')); continue; } $files[$file_hash] = array('name' => $file_name, 'file' => $file_url); } } // grant permission to any newly added files on any existing orders for this product prior to saving do_action('woocommerce_process_product_file_download_paths', $post_id, $variation_id, $files); update_post_meta($variation_id, '_downloadable_files', $files); } else { update_post_meta($variation_id, '_download_limit', ''); update_post_meta($variation_id, '_download_expiry', ''); update_post_meta($variation_id, '_downloadable_files', ''); } update_post_meta($variation_id, '_variation_description', wp_kses_post($variable_description[$i])); // Save shipping class $variable_shipping_class[$i] = !empty($variable_shipping_class[$i]) ? (int) $variable_shipping_class[$i] : ''; wp_set_object_terms($variation_id, $variable_shipping_class[$i], 'product_shipping_class'); // Update Attributes $updated_attribute_keys = array(); foreach ($attributes as $attribute) { if ($attribute['is_variation']) { $attribute_key = 'attribute_' . sanitize_title($attribute['name']); $updated_attribute_keys[] = $attribute_key; if ($attribute['is_taxonomy']) { // Don't use wc_clean as it destroys sanitized characters $value = isset($_POST[$attribute_key][$i]) ? sanitize_title(stripslashes($_POST[$attribute_key][$i])) : ''; } else { $value = isset($_POST[$attribute_key][$i]) ? wc_clean(stripslashes($_POST[$attribute_key][$i])) : ''; } update_post_meta($variation_id, $attribute_key, $value); } } // Remove old taxonomies attributes so data is kept up to date - first get attribute key names $delete_attribute_keys = $wpdb->get_col($wpdb->prepare("SELECT meta_key FROM {$wpdb->postmeta} WHERE meta_key LIKE 'attribute_%%' AND meta_key NOT IN ( '" . implode("','", $updated_attribute_keys) . "' ) AND post_id = %d;", $variation_id)); foreach ($delete_attribute_keys as $key) { delete_post_meta($variation_id, $key); } do_action('woocommerce_save_product_variation', $variation_id, $i); } } // Update parent if variable so price sorting works and stays in sync with the cheapest child WC_Product_Variable::sync($post_id); // Update default attribute options setting $default_attributes = array(); foreach ($attributes as $attribute) { if ($attribute['is_variation']) { // Don't use wc_clean as it destroys sanitized characters if (isset($_POST['default_attribute_' . sanitize_title($attribute['name'])])) { $value = sanitize_title(trim(stripslashes($_POST['default_attribute_' . sanitize_title($attribute['name'])]))); } else { $value = ''; } if ($value) { $default_attributes[sanitize_title($attribute['name'])] = $value; } } } update_post_meta($post_id, '_default_attributes', $default_attributes); }
/** * Prepare a single order output for response. * * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. * @return WP_REST_Response $data */ public function prepare_item_for_response($post, $request) { global $wpdb; $order = wc_get_order($post); $dp = $request['dp']; $data = array('id' => $order->id, 'parent_id' => $post->post_parent, 'status' => $order->get_status(), 'order_key' => $order->order_key, 'currency' => $order->get_order_currency(), 'version' => $order->order_version, 'prices_include_tax' => $order->prices_include_tax, 'date_created' => wc_rest_prepare_date_response($post->post_date_gmt), 'date_modified' => wc_rest_prepare_date_response($post->post_modified_gmt), 'customer_id' => $order->get_user_id(), 'discount_total' => wc_format_decimal($order->get_total_discount(), $dp), 'discount_tax' => wc_format_decimal($order->cart_discount_tax, $dp), 'shipping_total' => wc_format_decimal($order->get_total_shipping(), $dp), 'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp), 'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp), 'total' => wc_format_decimal($order->get_total(), $dp), 'total_tax' => wc_format_decimal($order->get_total_tax(), $dp), 'billing' => array(), 'shipping' => array(), 'payment_method' => $order->payment_method, 'payment_method_title' => $order->payment_method_title, 'transaction_id' => $order->get_transaction_id(), 'customer_ip_address' => $order->customer_ip_address, 'customer_user_agent' => $order->customer_user_agent, 'created_via' => $order->created_via, 'customer_note' => $order->customer_note, 'date_completed' => wc_rest_prepare_date_response($order->completed_date), 'date_paid' => $order->paid_date, 'cart_hash' => $order->cart_hash, 'line_items' => array(), 'tax_lines' => array(), 'shipping_lines' => array(), 'fee_lines' => array(), 'coupon_lines' => array(), 'refunds' => array()); // Add addresses. $data['billing'] = $order->get_address('billing'); $data['shipping'] = $order->get_address('shipping'); // Add line items. foreach ($order->get_items() as $item_id => $item) { $product = $order->get_product_from_item($item); $product_id = 0; $variation_id = 0; $product_sku = null; // Check if the product exists. if (is_object($product)) { $product_id = $product->id; $variation_id = $product->variation_id; $product_sku = $product->get_sku(); } $meta = new WC_Order_Item_Meta($item, $product); $item_meta = array(); $hideprefix = 'true' === $request['all_item_meta'] ? null : '_'; foreach ($meta->get_formatted($hideprefix) as $meta_key => $formatted_meta) { $item_meta[] = array('key' => $formatted_meta['key'], 'label' => $formatted_meta['label'], 'value' => $formatted_meta['value']); } $line_item = array('id' => $item_id, 'name' => $item['name'], 'sku' => $product_sku, 'product_id' => (int) $product_id, 'variation_id' => (int) $variation_id, 'quantity' => wc_stock_amount($item['qty']), 'tax_class' => !empty($item['tax_class']) ? $item['tax_class'] : '', 'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp), 'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp), 'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp), 'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp), 'total_tax' => wc_format_decimal($item['line_tax'], $dp), 'taxes' => array(), 'meta' => $item_meta); $item_line_taxes = maybe_unserialize($item['line_tax_data']); if (isset($item_line_taxes['total'])) { $line_tax = array(); foreach ($item_line_taxes['total'] as $tax_rate_id => $tax) { $line_tax[$tax_rate_id] = array('id' => $tax_rate_id, 'total' => $tax, 'subtotal' => ''); } foreach ($item_line_taxes['subtotal'] as $tax_rate_id => $tax) { $line_tax[$tax_rate_id]['subtotal'] = $tax; } $line_item['taxes'] = array_values($line_tax); } $data['line_items'][] = $line_item; } // Add taxes. foreach ($order->get_items('tax') as $key => $tax) { $tax_line = array('id' => $key, 'rate_code' => $tax['name'], 'rate_id' => $tax['rate_id'], 'label' => isset($tax['label']) ? $tax['label'] : $tax['name'], 'compound' => (bool) $tax['compound'], 'tax_total' => wc_format_decimal($tax['tax_amount'], $dp), 'shipping_tax_total' => wc_format_decimal($tax['shipping_tax_amount'], $dp)); $data['tax_lines'][] = $tax_line; } // Add shipping. foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) { $shipping_line = array('id' => $shipping_item_id, 'method_title' => $shipping_item['name'], 'method_id' => $shipping_item['method_id'], 'total' => wc_format_decimal($shipping_item['cost'], $dp), 'total_tax' => wc_format_decimal('', $dp), 'taxes' => array()); $shipping_taxes = maybe_unserialize($shipping_item['taxes']); if (!empty($shipping_taxes)) { $shipping_line['total_tax'] = wc_format_decimal(array_sum($shipping_taxes), $dp); foreach ($shipping_taxes as $tax_rate_id => $tax) { $shipping_line['taxes'][] = array('id' => $tax_rate_id, 'total' => $tax); } } $data['shipping_lines'][] = $shipping_line; } // Add fees. foreach ($order->get_fees() as $fee_item_id => $fee_item) { $fee_line = array('id' => $fee_item_id, 'name' => $fee_item['name'], 'tax_class' => !empty($fee_item['tax_class']) ? $fee_item['tax_class'] : '', 'tax_status' => 'taxable', 'total' => wc_format_decimal($order->get_line_total($fee_item), $dp), 'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp), 'taxes' => array()); $fee_line_taxes = maybe_unserialize($fee_item['line_tax_data']); if (isset($fee_line_taxes['total'])) { $fee_tax = array(); foreach ($fee_line_taxes['total'] as $tax_rate_id => $tax) { $fee_tax[$tax_rate_id] = array('id' => $tax_rate_id, 'total' => $tax, 'subtotal' => ''); } foreach ($fee_line_taxes['subtotal'] as $tax_rate_id => $tax) { $fee_tax[$tax_rate_id]['subtotal'] = $tax; } $fee_line['taxes'] = array_values($fee_tax); } $data['fee_lines'][] = $fee_line; } // Add coupons. foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) { $coupon_line = array('id' => $coupon_item_id, 'code' => $coupon_item['name'], 'discount' => wc_format_decimal($coupon_item['discount_amount'], $dp), 'discount_tax' => wc_format_decimal($coupon_item['discount_amount_tax'], $dp)); $data['coupon_lines'][] = $coupon_line; } // Add refunds. foreach ($order->get_refunds() as $refund) { $data['refunds'][] = array('id' => $refund->id, 'refund' => $refund->get_refund_reason() ? $refund->get_refund_reason() : '', 'total' => '-' . wc_format_decimal($refund->get_refund_amount(), $dp)); } $context = !empty($request['context']) ? $request['context'] : 'view'; $data = $this->add_additional_fields_to_object($data, $request); $data = $this->filter_response_by_context($data, $context); // Wrap the data in a response object. $response = rest_ensure_response($data); $response->add_links($this->prepare_links($order)); /** * Filter the data for a response. * * The dynamic portion of the hook name, $this->post_type, refers to post_type of the post being * prepared for the response. * * @param WP_REST_Response $response The response object. * @param WP_Post $post Post object. * @param WP_REST_Request $request Request object. */ return apply_filters("woocommerce_rest_prepare_{$this->post_type}", $response, $post, $request); }
<?php if ($product->is_in_stock()) { ?> <?php do_action('woocommerce_before_add_to_cart_form'); ?> <form class="cart" method="post" enctype='multipart/form-data'> <?php do_action('woocommerce_before_add_to_cart_button'); ?> <?php if (!$product->is_sold_individually()) { woocommerce_quantity_input(array('min_value' => apply_filters('woocommerce_quantity_input_min', 1, $product), 'max_value' => apply_filters('woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product), 'input_value' => isset($_POST['quantity']) ? wc_stock_amount($_POST['quantity']) : 1)); } ?> <input type="hidden" name="add-to-cart" value="<?php echo esc_attr($product->id); ?> " /> <button type="submit" class="single_add_to_cart_button button alt"><?php echo esc_html($product->single_add_to_cart_text()); ?> </button> <?php do_action('woocommerce_after_add_to_cart_button');
/** * Returns number of items available for sale. * * @return int */ public function get_stock_quantity() { return apply_filters('woocommerce_get_stock_quantity', $this->managing_stock() ? wc_stock_amount($this->stock) : '', $this); }
/** * 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'); } } } }
setup_postdata($post); ?> <tr> <td> <?php if ($product->is_sold_individually() || !$product->is_purchasable()) { ?> <?php woocommerce_template_loop_add_to_cart(); ?> <?php } else { ?> <?php $quantites_required = true; woocommerce_quantity_input(array('input_name' => 'quantity[' . $product_id . ']', 'input_value' => isset($_POST['quantity'][$product_id]) ? wc_stock_amount($_POST['quantity'][$product_id]) : 0, 'min_value' => apply_filters('woocommerce_quantity_input_min', 0, $product), 'max_value' => apply_filters('woocommerce_quantity_input_max', $product->backorders_allowed() ? '' : $product->get_stock_quantity(), $product))); ?> <?php } ?> </td> <td class="label"> <label for="product-<?php echo $product_id; ?> "> <?php echo $product->is_visible() ? '<a href="' . esc_url(apply_filters('woocommerce_grouped_product_list_link', get_permalink(), $product_id)) . '">' . esc_html(get_the_title()) . '</a>' : esc_html(get_the_title()); ?> </label>
/** * 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; }
/** * Update a line item for the order * * Note this does not update order totals * * @since 2.2 * @param int $item_id order item ID * @param array $args data to update * @param WC_Product $product * @return bool */ public function update_product($item_id, $product, $args) { if (!$item_id || !is_object($product)) { return false; } // quantity if (isset($args['qty'])) { wc_update_order_item_meta($item_id, '_qty', wc_stock_amount($args['qty'])); } // tax class if (isset($args['tax_class'])) { wc_update_order_item_meta($item_id, '_tax_class', $args['tax_class']); } // set item totals, either provided or from product if (isset($args['qty'])) { wc_update_order_item_meta($item_id, '_line_subtotal', wc_format_decimal(isset($args['totals']['subtotal']) ? $args['totals']['subtotal'] : $product->get_price_excluding_tax($args['qty']))); wc_update_order_item_meta($item_id, '_line_total', wc_format_decimal(isset($args['totals']['total']) ? $args['totals']['total'] : $product->get_price_excluding_tax($args['qty']))); } // set item tax totals wc_update_order_item_meta($item_id, '_line_subtotal_tax', wc_format_decimal(isset($args['totals']['subtotal_tax']) ? $args['totals']['subtotal_tax'] : 0)); wc_update_order_item_meta($item_id, '_line_tax', wc_format_decimal(isset($args['totals']['tax']) ? $args['totals']['tax'] : 0)); // variation meta if (isset($args['variation']) && is_array($args['variation'])) { foreach ($args['variation'] as $key => $value) { wc_update_order_item_meta($item_id, str_replace('attribute_', '', $key), $value); } } // backorders if (isset($args['qty']) && $product->backorders_require_notification() && $product->is_on_backorder($args['qty'])) { wc_update_order_item_meta($item_id, apply_filters('woocommerce_backordered_item_meta_name', __('Backordered', 'woocommerce')), $args['qty'] - max(0, $product->get_total_stock())); } do_action('woocommerce_order_edit_product', $this->id, $item_id, $args, $product); return true; }
/** * Get the order data for the given ID. * * @since 2.5.0 * @param WC_Order $order The order instance * @return array */ protected function get_order_data($order) { $order_post = get_post($order->id); $dp = wc_get_price_decimals(); $order_data = array('id' => $order->id, 'order_number' => $order->get_order_number(), 'created_at' => $this->format_datetime($order_post->post_date_gmt), 'updated_at' => $this->format_datetime($order_post->post_modified_gmt), 'completed_at' => $this->format_datetime($order->completed_date, true), 'status' => $order->get_status(), 'currency' => $order->get_order_currency(), 'total' => wc_format_decimal($order->get_total(), $dp), 'subtotal' => wc_format_decimal($order->get_subtotal(), $dp), 'total_line_items_quantity' => $order->get_item_count(), 'total_tax' => wc_format_decimal($order->get_total_tax(), $dp), 'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp), 'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp), 'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp), 'total_discount' => wc_format_decimal($order->get_total_discount(), $dp), 'shipping_methods' => $order->get_shipping_method(), 'payment_details' => array('method_id' => $order->payment_method, 'method_title' => $order->payment_method_title, 'paid' => isset($order->paid_date)), 'billing_address' => array('first_name' => $order->billing_first_name, 'last_name' => $order->billing_last_name, 'company' => $order->billing_company, 'address_1' => $order->billing_address_1, 'address_2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postcode' => $order->billing_postcode, 'country' => $order->billing_country, 'email' => $order->billing_email, 'phone' => $order->billing_phone), 'shipping_address' => array('first_name' => $order->shipping_first_name, 'last_name' => $order->shipping_last_name, 'company' => $order->shipping_company, 'address_1' => $order->shipping_address_1, 'address_2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postcode' => $order->shipping_postcode, 'country' => $order->shipping_country), 'note' => $order->customer_note, 'customer_ip' => $order->customer_ip_address, 'customer_user_agent' => $order->customer_user_agent, 'customer_id' => $order->get_user_id(), 'view_order_url' => $order->get_view_order_url(), 'line_items' => array(), 'shipping_lines' => array(), 'tax_lines' => array(), 'fee_lines' => array(), 'coupon_lines' => array()); // add line items foreach ($order->get_items() as $item_id => $item) { $product = $order->get_product_from_item($item); $product_id = null; $product_sku = null; // Check if the product exists. if (is_object($product)) { $product_id = isset($product->variation_id) ? $product->variation_id : $product->id; $product_sku = $product->get_sku(); } $meta = new WC_Order_Item_Meta($item, $product); $item_meta = array(); foreach ($meta->get_formatted(null) as $meta_key => $formatted_meta) { $item_meta[] = array('key' => $meta_key, 'label' => $formatted_meta['label'], 'value' => $formatted_meta['value']); } $order_data['line_items'][] = array('id' => $item_id, 'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp), 'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp), 'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp), 'total_tax' => wc_format_decimal($item['line_tax'], $dp), 'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp), 'quantity' => wc_stock_amount($item['qty']), 'tax_class' => !empty($item['tax_class']) ? $item['tax_class'] : null, 'name' => $item['name'], 'product_id' => $product_id, 'sku' => $product_sku, 'meta' => $item_meta); } // Add shipping. foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) { $order_data['shipping_lines'][] = array('id' => $shipping_item_id, 'method_id' => $shipping_item['method_id'], 'method_title' => $shipping_item['name'], 'total' => wc_format_decimal($shipping_item['cost'], $dp)); } // Add taxes. foreach ($order->get_tax_totals() as $tax_code => $tax) { $order_data['tax_lines'][] = array('id' => $tax->id, 'rate_id' => $tax->rate_id, 'code' => $tax_code, 'title' => $tax->label, 'total' => wc_format_decimal($tax->amount, $dp), 'compound' => (bool) $tax->is_compound); } // Add fees. foreach ($order->get_fees() as $fee_item_id => $fee_item) { $order_data['fee_lines'][] = array('id' => $fee_item_id, 'title' => $fee_item['name'], 'tax_class' => !empty($fee_item['tax_class']) ? $fee_item['tax_class'] : null, 'total' => wc_format_decimal($order->get_line_total($fee_item), $dp), 'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp)); } // Add coupons. foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) { $order_data['coupon_lines'][] = array('id' => $coupon_item_id, 'code' => $coupon_item['name'], 'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp)); } $order_data = apply_filters('woocommerce_cli_order_data', $order_data); return $this->flatten_array($order_data); }
/** * @param $line_items * @return mixed */ private function filter_qty($line_items) { foreach ($line_items as &$item) { $qty = wc_get_order_item_meta($item['id'], '_qty'); $item['quantity'] = wc_stock_amount($qty); } return $line_items; }
/** * Get quantity. * @return int */ public function get_quantity() { return wc_stock_amount($this->_data['quantity']); }
/** * 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); }
/** * Add to cart action * * Checks for a valid request, does validation (via hooks) and then redirects if valid. * * @param bool $url (default: false) */ public static function add_to_cart_action($url = false) { if (empty($_REQUEST['add-to-cart']) || !is_numeric($_REQUEST['add-to-cart'])) { return; } $product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_REQUEST['add-to-cart'])); $was_added_to_cart = false; $added_to_cart = array(); $adding_to_cart = wc_get_product($product_id); $add_to_cart_handler = apply_filters('woocommerce_add_to_cart_handler', $adding_to_cart->product_type, $adding_to_cart); // Check if the product is published if ('publish' !== $adding_to_cart->post->post_status) { wc_add_notice(__('Sorry, this product is unavailable.', 'woocommerce'), 'error'); return; } // Variable product handling if ('variable' === $add_to_cart_handler) { $variation_id = empty($_REQUEST['variation_id']) ? '' : absint($_REQUEST['variation_id']); $quantity = empty($_REQUEST['quantity']) ? 1 : wc_stock_amount($_REQUEST['quantity']); $missing_attributes = array(); $variations = array(); $attributes = $adding_to_cart->get_attributes(); $variation = wc_get_product($variation_id); // Verify all attributes foreach ($attributes as $attribute) { if (!$attribute['is_variation']) { continue; } $taxonomy = 'attribute_' . sanitize_title($attribute['name']); if (isset($_REQUEST[$taxonomy])) { // Get value from post data if ($attribute['is_taxonomy']) { // Don't use wc_clean as it destroys sanitized characters $value = sanitize_title(stripslashes($_REQUEST[$taxonomy])); } else { $value = wc_clean(stripslashes($_REQUEST[$taxonomy])); } // Get valid value from variation $valid_value = $variation->variation_data[$taxonomy]; // Allow if valid if ('' === $valid_value || $valid_value === $value) { // Pre 2.4 handling where 'slugs' were saved instead of the full text attribute if (!$attribute['is_taxonomy']) { if ($value === sanitize_title($value) && version_compare(get_post_meta($product_id, '_product_version', true), '2.4.0', '<')) { $text_attributes = wc_get_text_attributes($attribute['value']); foreach ($text_attributes as $text_attribute) { if (sanitize_title($text_attribute) === $value) { $value = $text_attribute; break; } } } } $variations[$taxonomy] = $value; continue; } } else { $missing_attributes[] = wc_attribute_label($attribute['name']); } } if ($missing_attributes) { wc_add_notice(sprintf(_n('%s is a required field', '%s are required fields', sizeof($missing_attributes), 'woocommerce'), wc_format_list_of_items($missing_attributes)), 'error'); return; } elseif (empty($variation_id)) { wc_add_notice(__('Please choose product options…', 'woocommerce'), 'error'); return; } else { // Add to cart validation $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations); if ($passed_validation) { if (WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variations) !== false) { wc_add_to_cart_message($product_id); $was_added_to_cart = true; $added_to_cart[] = $product_id; } } } // Grouped Products } elseif ('grouped' === $add_to_cart_handler) { if (!empty($_REQUEST['quantity']) && is_array($_REQUEST['quantity'])) { $quantity_set = false; foreach ($_REQUEST['quantity'] as $item => $quantity) { if ($quantity <= 0) { continue; } $quantity_set = true; // Add to cart validation $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $item, $quantity); if ($passed_validation) { if (WC()->cart->add_to_cart($item, $quantity) !== false) { $was_added_to_cart = true; $added_to_cart[] = $item; } } } if ($was_added_to_cart) { wc_add_to_cart_message($added_to_cart); } if (!$was_added_to_cart && !$quantity_set) { wc_add_notice(__('Please choose the quantity of items you wish to add to your cart…', 'woocommerce'), 'error'); return; } } elseif ($product_id) { /* Link on product archives */ wc_add_notice(__('Please choose a product to add to your cart…', 'woocommerce'), 'error'); return; } // Custom Handler } elseif (has_action('woocommerce_add_to_cart_handler_' . $add_to_cart_handler)) { do_action('woocommerce_add_to_cart_handler_' . $add_to_cart_handler, $url); return; // Simple Products } else { $quantity = empty($_REQUEST['quantity']) ? 1 : wc_stock_amount($_REQUEST['quantity']); // Add to cart validation $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity); if ($passed_validation) { // Add the product to the cart if (WC()->cart->add_to_cart($product_id, $quantity) !== false) { wc_add_to_cart_message($product_id); $was_added_to_cart = true; $added_to_cart[] = $product_id; } } } // If we added the product to the cart we can now optionally do a redirect. if ($was_added_to_cart && wc_notice_count('error') == 0) { $url = apply_filters('woocommerce_add_to_cart_redirect', $url); // If has custom URL redirect there if ($url) { wp_safe_redirect($url); exit; } elseif (get_option('woocommerce_cart_redirect_after_add') == 'yes') { wp_safe_redirect(WC()->cart->get_cart_url()); exit; } } }
/** * Get the order for the given ID * * @since 2.1 * @param int $id the order ID * @param array $fields * @param array $filter * @return array */ public function get_order($id, $fields = null, $filter = array()) { // ensure order ID is valid & user has permission to read $id = $this->validate_request($id, $this->post_type, 'read'); if (is_wp_error($id)) { return $id; } // Get the decimal precession $dp = isset($filter['dp']) ? intval($filter['dp']) : 2; $order = wc_get_order($id); $order_post = get_post($id); $order_data = array('id' => $order->id, 'order_number' => $order->get_order_number(), 'created_at' => $this->server->format_datetime($order_post->post_date_gmt), 'updated_at' => $this->server->format_datetime($order_post->post_modified_gmt), 'completed_at' => $this->server->format_datetime($order->completed_date, true), 'status' => $order->get_status(), 'currency' => $order->get_order_currency(), 'total' => wc_format_decimal($order->get_total(), $dp), 'subtotal' => wc_format_decimal($order->get_subtotal(), $dp), 'total_line_items_quantity' => $order->get_item_count(), 'total_tax' => wc_format_decimal($order->get_total_tax(), $dp), 'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp), 'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp), 'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp), 'total_discount' => wc_format_decimal($order->get_total_discount(), $dp), 'shipping_methods' => $order->get_shipping_method(), 'payment_details' => array('method_id' => $order->payment_method, 'method_title' => $order->payment_method_title, 'paid' => isset($order->paid_date)), 'billing_address' => array('first_name' => $order->billing_first_name, 'last_name' => $order->billing_last_name, 'company' => $order->billing_company, 'address_1' => $order->billing_address_1, 'address_2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postcode' => $order->billing_postcode, 'country' => $order->billing_country, 'email' => $order->billing_email, 'phone' => $order->billing_phone), 'shipping_address' => array('first_name' => $order->shipping_first_name, 'last_name' => $order->shipping_last_name, 'company' => $order->shipping_company, 'address_1' => $order->shipping_address_1, 'address_2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postcode' => $order->shipping_postcode, 'country' => $order->shipping_country), 'note' => $order->customer_note, 'customer_ip' => $order->customer_ip_address, 'customer_user_agent' => $order->customer_user_agent, 'customer_id' => $order->get_user_id(), 'view_order_url' => $order->get_view_order_url(), 'line_items' => array(), 'shipping_lines' => array(), 'tax_lines' => array(), 'fee_lines' => array(), 'coupon_lines' => array()); // add line items foreach ($order->get_items() as $item_id => $item) { $product = $order->get_product_from_item($item); $product_id = null; $product_sku = null; // Check if the product exists. if (is_object($product)) { $product_id = isset($product->variation_id) ? $product->variation_id : $product->id; $product_sku = $product->get_sku(); } $meta = new WC_Order_Item_Meta($item, $product); $item_meta = array(); $hideprefix = isset($filter['all_item_meta']) && $filter['all_item_meta'] === 'true' ? null : '_'; foreach ($meta->get_formatted($hideprefix) as $meta_key => $formatted_meta) { $item_meta[] = array('key' => $formatted_meta['key'], 'label' => $formatted_meta['label'], 'value' => $formatted_meta['value']); } $order_data['line_items'][] = array('id' => $item_id, 'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp), 'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp), 'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp), 'total_tax' => wc_format_decimal($item['line_tax'], $dp), 'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp), 'quantity' => wc_stock_amount($item['qty']), 'tax_class' => !empty($item['tax_class']) ? $item['tax_class'] : null, 'name' => $item['name'], 'product_id' => $product_id, 'sku' => $product_sku, 'meta' => $item_meta); } // add shipping foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) { $order_data['shipping_lines'][] = array('id' => $shipping_item_id, 'method_id' => $shipping_item['method_id'], 'method_title' => $shipping_item['name'], 'total' => wc_format_decimal($shipping_item['cost'], $dp)); } // add taxes foreach ($order->get_tax_totals() as $tax_code => $tax) { $order_data['tax_lines'][] = array('id' => $tax->id, 'rate_id' => $tax->rate_id, 'code' => $tax_code, 'title' => $tax->label, 'total' => wc_format_decimal($tax->amount, $dp), 'compound' => (bool) $tax->is_compound); } // add fees foreach ($order->get_fees() as $fee_item_id => $fee_item) { $order_data['fee_lines'][] = array('id' => $fee_item_id, 'title' => $fee_item['name'], 'tax_class' => !empty($fee_item['tax_class']) ? $fee_item['tax_class'] : null, 'total' => wc_format_decimal($order->get_line_total($fee_item), $dp), 'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp)); } // add coupons foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) { $order_data['coupon_lines'][] = array('id' => $coupon_item_id, 'code' => $coupon_item['name'], 'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp)); } return array('order' => apply_filters('woocommerce_api_order_response', $order_data, $order, $fields, $this->server)); }
/** * Handle adding variable products to the cart. * @since 2.4.6 Split from add_to_cart_action * @param int $product_id * @return bool success or not */ private static function add_to_cart_handler_variable($product_id) { $adding_to_cart = wc_get_product($product_id); $variation_id = empty($_REQUEST['variation_id']) ? '' : absint($_REQUEST['variation_id']); $quantity = empty($_REQUEST['quantity']) ? 1 : wc_stock_amount($_REQUEST['quantity']); $missing_attributes = array(); $variations = array(); $attributes = $adding_to_cart->get_attributes(); // If no variation ID is set, attempt to get a variation ID from posted attributes. if (empty($variation_id)) { $variation_id = $adding_to_cart->get_matching_variation(wp_unslash($_POST)); } $variation = wc_get_product($variation_id); // Validate the attributes. try { if (empty($variation_id)) { throw new Exception(__('Please choose product options…', 'woocommerce')); } foreach ($attributes as $attribute) { if (!$attribute['is_variation']) { continue; } $taxonomy = 'attribute_' . sanitize_title($attribute['name']); if (isset($_REQUEST[$taxonomy])) { // Get value from post data if ($attribute['is_taxonomy']) { // Don't use wc_clean as it destroys sanitized characters $value = sanitize_title(stripslashes($_REQUEST[$taxonomy])); } else { $value = wc_clean(stripslashes($_REQUEST[$taxonomy])); } // Get valid value from variation $valid_value = isset($variation->variation_data[$taxonomy]) ? $variation->variation_data[$taxonomy] : ''; // Allow if valid or show error. if ('' === $valid_value || $valid_value === $value) { $variations[$taxonomy] = $value; } else { throw new Exception(sprintf(__('Invalid value posted for %s', 'woocommerce'), wc_attribute_label($attribute['name']))); } } else { $missing_attributes[] = wc_attribute_label($attribute['name']); } } if (!empty($missing_attributes)) { throw new Exception(sprintf(_n('%s is a required field', '%s are required fields', sizeof($missing_attributes), 'woocommerce'), wc_format_list_of_items($missing_attributes))); } } catch (Exception $e) { wc_add_notice($e->getMessage(), 'error'); return false; } // Add to cart validation $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations); if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variations) !== false) { wc_add_to_cart_message(array($product_id => $quantity), true); return true; } return false; }
?> <div class="show_if_variation_manage_stock" style="display: none;"> <p class="form-row form-row-first"> <label><?php _e('Stock quantity', 'woocommerce'); ?> <?php echo wc_help_tip(__('Enter a quantity to enable stock management at variation level, or leave blank to use the parent product\'s options.', 'woocommerce')); ?> </label> <input type="number" size="5" name="variable_stock[<?php echo $loop; ?> ]" value="<?php if (isset($_stock)) { echo esc_attr(wc_stock_amount($_stock)); } ?> " step="any" /> </p> <p class="form-row form-row-last"> <label><?php _e('Allow backorders?', 'woocommerce'); ?> </label> <select name="variable_backorders[<?php echo $loop; ?> ]"> <?php foreach ($parent_data['backorder_options'] as $key => $value) {
/** * Returns number of items available for sale from the variation, or parent. * * @return int */ public function get_stock_quantity() { return true === $this->managing_stock() ? wc_stock_amount($this->stock) : $this->parent->get_stock_quantity(); }
/** * Get total stock. * * This is the stock of parent and children combined. * * @return int */ public function get_total_stock() { if (empty($this->total_stock)) { $this->total_stock = max(0, $this->get_stock_quantity()); if (sizeof($this->get_children()) > 0) { foreach ($this->get_children() as $child_id) { if ('yes' === get_post_meta($child_id, '_manage_stock', true)) { $stock = get_post_meta($child_id, '_stock', true); $this->total_stock += max(0, wc_stock_amount($stock)); } } } } return wc_stock_amount($this->total_stock); }
/** * Returns number of items available for sale. * * @return int */ public function get_stock_quantity() { return $this->managing_stock() ? wc_stock_amount($this->stock) : ''; }
/** * Handle adding variable products to the cart * @since 2.4.6 Split from add_to_cart_action * @param int $product_id * @return bool success or not */ private static function add_to_cart_handler_variable($product_id) { $adding_to_cart = wc_get_product($product_id); $variation_id = empty($_REQUEST['variation_id']) ? '' : absint($_REQUEST['variation_id']); $quantity = empty($_REQUEST['quantity']) ? 1 : wc_stock_amount($_REQUEST['quantity']); $missing_attributes = array(); $variations = array(); $attributes = $adding_to_cart->get_attributes(); $variation = wc_get_product($variation_id); // Verify all attributes foreach ($attributes as $attribute) { if (!$attribute['is_variation']) { continue; } $taxonomy = 'attribute_' . sanitize_title($attribute['name']); if (isset($_REQUEST[$taxonomy])) { // Get value from post data if ($attribute['is_taxonomy']) { // Don't use wc_clean as it destroys sanitized characters $value = sanitize_title(stripslashes($_REQUEST[$taxonomy])); } else { $value = wc_clean(stripslashes($_REQUEST[$taxonomy])); } // Get valid value from variation $valid_value = $variation->variation_data[$taxonomy]; // Allow if valid if ('' === $valid_value || $valid_value === $value) { $variations[$taxonomy] = $value; continue; } } else { $missing_attributes[] = wc_attribute_label($attribute['name']); } } if ($missing_attributes) { wc_add_notice(sprintf(_n('%s is a required field', '%s are required fields', sizeof($missing_attributes), 'woocommerce'), wc_format_list_of_items($missing_attributes)), 'error'); } elseif (empty($variation_id)) { wc_add_notice(__('Please choose product options…', 'woocommerce'), 'error'); } else { // Add to cart validation $passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity, $variation_id, $variations); if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $variations) !== false) { wc_add_to_cart_message($product_id); return true; } } return false; }