コード例 #1
1
 /**
  * Add order item via ajax
  * exact copy from /wp-content/plugins/woocommerce/includes/class-wc-ajax.php, with change to template selection
  */
 public static function add_order_item()
 {
     check_ajax_referer('order-item', 'security');
     $item_to_add = sanitize_text_field($_POST['item_to_add']);
     $order_id = absint($_POST['order_id']);
     // Find the item
     if (!is_numeric($item_to_add)) {
         die;
     }
     $post = get_post($item_to_add);
     if (!$post || 'product' !== $post->post_type && 'product_variation' !== $post->post_type) {
         die;
     }
     $_product = wc_get_product($post->ID);
     $order = wc_get_order($order_id);
     $order_taxes = $order->get_taxes();
     $class = 'new_row';
     // Set values
     $item = array();
     $item['product_id'] = $_product->id;
     $item['variation_id'] = isset($_product->variation_id) ? $_product->variation_id : '';
     $item['variation_data'] = isset($_product->variation_data) ? $_product->variation_data : '';
     $item['name'] = $_product->get_title();
     $item['tax_class'] = $_product->get_tax_class();
     $item['qty'] = 1;
     $item['line_subtotal'] = wc_format_decimal($_product->get_price_excluding_tax());
     $item['line_subtotal_tax'] = '';
     $item['line_total'] = wc_format_decimal($_product->get_price_excluding_tax());
     $item['line_tax'] = '';
     // Add line item
     $item_id = wc_add_order_item($order_id, array('order_item_name' => $item['name'], 'order_item_type' => 'line_item'));
     // Add line item meta
     if ($item_id) {
         wc_add_order_item_meta($item_id, '_qty', $item['qty']);
         wc_add_order_item_meta($item_id, '_tax_class', $item['tax_class']);
         wc_add_order_item_meta($item_id, '_product_id', $item['product_id']);
         wc_add_order_item_meta($item_id, '_variation_id', $item['variation_id']);
         wc_add_order_item_meta($item_id, '_line_subtotal', $item['line_subtotal']);
         wc_add_order_item_meta($item_id, '_line_subtotal_tax', $item['line_subtotal_tax']);
         wc_add_order_item_meta($item_id, '_line_total', $item['line_total']);
         wc_add_order_item_meta($item_id, '_line_tax', $item['line_tax']);
         // Since 2.2
         wc_add_order_item_meta($item_id, '_line_tax_data', array('total' => array(), 'subtotal' => array()));
         // Store variation data in meta
         if ($item['variation_data'] && is_array($item['variation_data'])) {
             foreach ($item['variation_data'] as $key => $value) {
                 wc_add_order_item_meta($item_id, str_replace('attribute_', '', $key), $value);
             }
         }
         do_action('woocommerce_ajax_add_order_item_meta', $item_id, $item);
     }
     $item = apply_filters('woocommerce_ajax_order_item', $item, $item_id);
     //include( 'admin/meta-boxes/views/html-order-item.php' );
     //@@@@LOUSHOU - allow overtake of template
     include apply_filters('qsot-woo-template', 'meta-boxes/views/html-order-item.php', 'admin');
     // Quit out
     die;
 }
コード例 #2
1
 /**
  * Create a order.
  *
  * @since 2.4
  *
  * @return WC_Order Order object.
  */
 public static function create_order($customer_id = 1)
 {
     // Create product
     $product = WC_Helper_Product::create_simple_product();
     WC_Helper_Shipping::create_simple_flat_rate();
     $order_data = array('status' => 'pending', 'customer_id' => $customer_id, 'customer_note' => '', 'total' => '');
     $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
     // Required, else wc_create_order throws an exception
     $order = wc_create_order($order_data);
     // Add order products
     $order->add_product($product, 4);
     // Set billing address
     $order->set_billing_first_name('Jeroen');
     $order->set_billing_last_name('Sormani');
     $order->set_billing_company('WooCompany');
     $order->set_billing_address_1('WooAddress');
     $order->set_billing_address_2('');
     $order->set_billing_city('WooCity');
     $order->set_billing_state('NY');
     $order->set_billing_postcode('123456');
     $order->set_billing_country('US');
     $order->set_billing_email('*****@*****.**');
     $order->set_billing_phone('555-32123');
     // Add shipping costs
     $shipping_taxes = WC_Tax::calc_shipping_tax('10', WC_Tax::get_shipping_tax_rates());
     $rate = new WC_Shipping_Rate('flat_rate_shipping', 'Flat rate shipping', '10', $shipping_taxes, 'flat_rate');
     $item = new WC_Order_Item_Shipping();
     $item->set_props(array('method_title' => $rate->label, 'method_id' => $rate->id, 'total' => wc_format_decimal($rate->cost), 'taxes' => $rate->taxes, 'meta_data' => $rate->get_meta_data()));
     $order->add_item($item);
     // Set payment gateway
     $payment_gateways = WC()->payment_gateways->payment_gateways();
     $order->set_payment_method($payment_gateways['bacs']);
     // Set totals
     $order->set_shipping_total(10);
     $order->set_discount_total(0);
     $order->set_discount_tax(0);
     $order->set_cart_tax(0);
     $order->set_shipping_tax(0);
     $order->set_total(40);
     // 4 x $10 simple helper product
     $order->save();
     return $order;
 }
コード例 #3
0
 public static function save($post_id)
 {
     if (isset($_POST['_unit'])) {
         update_post_meta($post_id, '_unit', sanitize_text_field($_POST['_unit']));
     }
     if (isset($_POST['_unit_base'])) {
         update_post_meta($post_id, '_unit_base', $_POST['_unit_base'] === '' ? '' : wc_format_decimal($_POST['_unit_base']));
     }
     if (isset($_POST['_unit_price_regular'])) {
         update_post_meta($post_id, '_unit_price_regular', $_POST['_unit_price_regular'] === '' ? '' : wc_format_decimal($_POST['_unit_price_regular']));
         update_post_meta($post_id, '_unit_price', $_POST['_unit_price_regular'] === '' ? '' : wc_format_decimal($_POST['_unit_price_regular']));
     }
     if (isset($_POST['_unit_price_sale'])) {
         update_post_meta($post_id, '_unit_price_sale', '');
         // Update Sale Price only if is on sale (Cron?!)
         if (get_post_meta($post_id, '_price', true) != $_POST['_regular_price'] && $_POST['_unit_price_sale'] !== '') {
             update_post_meta($post_id, '_unit_price_sale', $_POST['_unit_price_sale'] === '' ? '' : wc_format_decimal($_POST['_unit_price_sale']));
             update_post_meta($post_id, '_unit_price', $_POST['_unit_price_sale'] === '' ? '' : wc_format_decimal($_POST['_unit_price_sale']));
         }
     }
     if (isset($_POST['_mini_desc'])) {
         update_post_meta($post_id, '_mini_desc', esc_html($_POST['_mini_desc']));
     }
     if (isset($_POST['delivery_time']) && !is_numeric($_POST['delivery_time'])) {
         wp_set_post_terms($post_id, sanitize_text_field($_POST['delivery_time']), 'product_delivery_time');
     } else {
         wp_set_object_terms($post_id, absint($_POST['delivery_time']), 'product_delivery_time');
     }
 }
コード例 #4
0
ファイル: coupons.php プロジェクト: pelmered/woocommerce
 /**
  * Ensure valid coupon data response.
  * @since 2.7.0
  * @param array $response
  * @param WC_Coupon $coupon
  */
 protected function check_get_coupon_response($response, $coupon)
 {
     $this->assertEquals((int) $coupon->get_id(), $response['id']);
     $this->assertEquals($coupon->get_code(), $response['code']);
     $this->assertEquals($coupon->get_discount_type(), $response['type']);
     $this->assertEquals($coupon->get_amount(), $response['amount']);
     $this->assertEquals($coupon->get_individual_use(), $response['individual_use']);
     $this->assertEquals($coupon->get_product_ids(), $response['product_ids']);
     $this->assertEquals($coupon->get_excluded_product_ids(), $response['exclude_product_ids']);
     $this->assertEquals((int) $coupon->get_usage_limit(), $response['usage_limit']);
     $this->assertEquals((int) $coupon->get_usage_limit_per_user(), $response['usage_limit_per_user']);
     $this->assertEquals((int) $coupon->get_limit_usage_to_x_items(), $response['limit_usage_to_x_items']);
     $this->assertEquals((int) $coupon->get_usage_count(), $response['usage_count']);
     $this->assertEquals($coupon->get_expiry_date(), $response['expiry_date']);
     $this->assertEquals($coupon->get_free_shipping(), $response['enable_free_shipping']);
     $this->assertEquals($coupon->get_product_categories(), $response['product_category_ids']);
     $this->assertEquals($coupon->get_excluded_product_categories(), $response['exclude_product_category_ids']);
     $this->assertEquals($coupon->get_exclude_sale_items(), $response['exclude_sale_items']);
     $this->assertEquals(wc_format_decimal($coupon->get_minimum_amount(), 2), $response['minimum_amount']);
     $this->assertEquals(wc_format_decimal($coupon->get_maximum_amount(), 2), $response['maximum_amount']);
     $this->assertEquals($coupon->get_email_restrictions(), $response['customer_emails']);
     $this->assertEquals($coupon->get_description(), $response['description']);
     $this->assertArrayHasKey('created_at', $response);
     $this->assertArrayHasKey('updated_at', $response);
 }
コード例 #5
0
/**
 * Add weight to line item data
 *
 * @param array $line_item the original line item data
 * @param array $item the item's order data
 * @param object $product the \WC_Product object for the line
 * @param object $order the \WC_Order object being exported
 * @return array the updated line item data
 */
function sv_wc_csv_export_add_weight_to_line_item($line_item, $item, $product, $order)
{
    $new_item_data = array();
    foreach ($line_item as $key => $data) {
        $new_item_data[$key] = $data;
        if ('sku' === $key) {
            $new_item_data['weight'] = wc_format_decimal($product->get_weight(), 2);
        }
    }
    return $new_item_data;
}
コード例 #6
0
 /**
  * Get the coupon for the given ID
  *
  * @since 2.1
  * @param int $id the coupon ID
  * @param string $fields fields to include in response
  * @return array|WP_Error
  */
 public function get_coupon($id, $fields = null)
 {
     $id = $this->validate_request($id, 'shop_coupon', 'read');
     if (is_wp_error($id)) {
         return $id;
     }
     $coupon = new WC_Coupon($id);
     if (0 === $coupon->get_id()) {
         throw new WC_API_Exception('woocommerce_api_invalid_coupon_id', __('Invalid coupon ID', 'woocommerce'), 404);
     }
     $coupon_data = array('id' => $coupon->get_id(), 'code' => $coupon->get_code(), 'type' => $coupon->get_discount_type(), 'created_at' => $this->server->format_datetime($coupon->get_date_created(), false, true), 'updated_at' => $this->server->format_datetime($coupon->get_date_modified(), false, true), 'amount' => wc_format_decimal($coupon->get_amount(), 2), 'individual_use' => $coupon->get_individual_use(), 'product_ids' => array_map('absint', (array) $coupon->get_product_ids()), 'exclude_product_ids' => array_map('absint', (array) $coupon->get_excluded_product_ids()), 'usage_limit' => $coupon->get_usage_limit() ? $coupon->get_usage_limit() : null, 'usage_limit_per_user' => $coupon->get_usage_limit_per_user() ? $coupon->get_usage_limit_per_user() : null, 'limit_usage_to_x_items' => (int) $coupon->get_limit_usage_to_x_items(), 'usage_count' => (int) $coupon->get_usage_count(), 'expiry_date' => $this->server->format_datetime($coupon->get_date_expires(), false, true), 'enable_free_shipping' => $coupon->get_free_shipping(), 'product_category_ids' => array_map('absint', (array) $coupon->get_product_categories()), 'exclude_product_category_ids' => array_map('absint', (array) $coupon->get_excluded_product_categories()), 'exclude_sale_items' => $coupon->get_exclude_sale_items(), 'minimum_amount' => wc_format_decimal($coupon->get_minimum_amount(), 2), 'customer_emails' => $coupon->get_email_restrictions());
     return array('coupon' => apply_filters('woocommerce_api_coupon_response', $coupon_data, $coupon, $fields, $this->server));
 }
コード例 #7
0
ファイル: functions.php プロジェクト: nightbook/woocommerce
 /**
  * Test wc_get_product_ids_on_sale()
  *
  * @since 2.4
  */
 public function test_wc_get_product_ids_on_sale()
 {
     $this->assertEquals(array(), wc_get_product_ids_on_sale());
     delete_transient('wc_products_onsale');
     // Create product
     $product = \WC_Helper_Product::create_simple_product();
     update_post_meta($product->id, '_regular_price', wc_format_decimal(10));
     update_post_meta($product->id, '_price', wc_format_decimal(5));
     update_post_meta($product->id, '_sale_price', wc_format_decimal(5));
     $this->assertEquals(array($product->id), wc_get_product_ids_on_sale());
     // Delete Product
     \WC_Helper_Product::delete_product($product->id);
 }
 /**
  * Save the Targets settings
  */
 public function save()
 {
     try {
         $this->verify_request(WooCommerce_Grow_Helpers::get_field('_wpnonce', $_REQUEST), 'woocommerce-grow-targets');
         $is_calculate_growth = null !== WooCommerce_Grow_Helpers::get_field('calculate_growth', $_POST) ? true : false;
         // Calculate and Growth settings
         if ($is_calculate_growth) {
             $initial_revenue_number = WooCommerce_Grow_Helpers::get_field('initial_revenue_number', $_POST);
             $initial_orders_number = WooCommerce_Grow_Helpers::get_field('initial_orders_number', $_POST);
             $initial_sessions_number = WooCommerce_Grow_Helpers::get_field('initial_sessions_number', $_POST);
             $initial_cr_number = WooCommerce_Grow_Helpers::get_field('initial_cr_number', $_POST);
             $initial_aov_number = WooCommerce_Grow_Helpers::get_field('initial_aov_number', $_POST);
             // Call to GA to get sessions for the last month
             $ga = WooCommerce_Grow_Google_Analytics::get_instance();
             $month = date('m', strtotime('first day of previous month'));
             $year = date('Y');
             list($start_date, $end_date) = WooCommerce_Grow_Helpers::get_first_and_last_of_the_month($month, $year);
             $initial_sessions = $ga->get_sessions_for_month($month, $year);
             $filters = array('date_min' => $start_date, 'date_max' => $end_date);
             $reports = WooCommerce_Grow_Helpers::setup_wc_reports($filters);
             $initial_revenue = WooCommerce_Grow_Helpers::get_wc_total_sales($reports);
             $initial_orders = WooCommerce_Grow_Helpers::get_wc_total_orders($reports);
             WooCommerce_Grow_Helpers::add_debug_log('Revenue: ' . $initial_revenue);
             WooCommerce_Grow_Helpers::add_debug_log('Orders: ' . $initial_orders);
             $initial_cr = WooCommerce_Grow_Helpers::calculate_cr($initial_orders, $initial_sessions);
             $initial_aov = WooCommerce_Grow_Helpers::calculate_aov($initial_revenue, $initial_orders);
             $growth_rate = WooCommerce_Grow_Helpers::get_field('growth_rate', $_POST);
             // Save the initial options
             WooCommerce_Grow_Helpers::update_option('initial_revenue_number', $initial_revenue);
             WooCommerce_Grow_Helpers::update_option('initial_orders_number', $initial_orders);
             WooCommerce_Grow_Helpers::update_option('initial_sessions_number', $initial_sessions);
             WooCommerce_Grow_Helpers::update_option('initial_cr_number', $initial_cr);
             WooCommerce_Grow_Helpers::update_option('initial_aov_number', $initial_aov);
             WooCommerce_Grow_Helpers::update_option('growth_rate', $growth_rate);
             $months = WooCommerce_Grow_Helpers::get_twelve_months_ahead();
             foreach ($months as $month) {
                 $target_sessions = WooCommerce_Grow_Helpers::calculate_growth($initial_sessions, $growth_rate);
                 $target_cr = WooCommerce_Grow_Helpers::calculate_growth($initial_cr, $growth_rate);
                 $target_aov = WooCommerce_Grow_Helpers::calculate_growth($initial_aov, $growth_rate);
                 $targets['sessions_percentage'][$month['year']][$month['month']] = ceil($target_sessions);
                 $targets['cr_percentage'][$month['year']][$month['month']] = $target_cr;
                 $targets['aov_percentage'][$month['year']][$month['month']] = $target_aov;
                 $targets['revenue_percentage'][$month['year']][$month['month']] = wc_format_decimal($target_sessions * $target_cr * $target_aov, 2);
                 $targets['orders_percentage'][$month['year']][$month['month']] = ceil($target_sessions * $target_cr);
             }
             WooCommerce_Grow_Helpers::update_option('monthly_targets', $targets);
         }
     } catch (Exception $e) {
         WC_Admin_Settings::add_error($e->getMessage());
     }
 }
コード例 #9
0
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     // update pos_cash data
     $tendered = isset($_POST['pos-cash-tendered']) ? wc_format_decimal($_POST['pos-cash-tendered']) : 0;
     $change = isset($_POST['pos-cash-change']) ? wc_format_decimal($_POST['pos-cash-change']) : 0;
     update_post_meta($order_id, '_pos_cash_amount_tendered', $tendered);
     update_post_meta($order_id, '_pos_cash_change', $change);
     // payment complete
     $order->payment_complete();
     // Return thankyou redirect
     return array('result' => 'success');
 }
コード例 #10
0
 /**
  * Add a rate.
  *
  * Add a shipping rate. If taxes are not set they will be calculated based on cost.
  *
  * @param array $args (default: array())
  */
 public function add_rate($args = array())
 {
     $args = wp_parse_args($args, array('id' => '', 'label' => '', 'cost' => '0', 'taxes' => '', 'calc_tax' => 'per_order'));
     // Id and label are required
     if (!$args['id'] || !$args['label']) {
         return;
     }
     // Total up the cost
     $total_cost = wc_format_decimal(is_array($args['cost']) ? array_sum($args['cost']) : $args['cost'], wc_get_price_decimals());
     $taxes = $args['taxes'];
     // Taxes - if not an array and not set to false, calc tax based on cost and passed calc_tax variable
     // This saves shipping methods having to do complex tax calculations
     if (!is_array($taxes) && $taxes !== false && $total_cost > 0 && $this->is_taxable()) {
         $taxes = array();
         switch ($args['calc_tax']) {
             case "per_item":
                 // If we have an array of costs we can look up each items tax class and add tax accordingly
                 if (is_array($args['cost'])) {
                     $cart = WC()->cart->get_cart();
                     foreach ($args['cost'] as $cost_key => $amount) {
                         if (!isset($cart[$cost_key])) {
                             continue;
                         }
                         $item_taxes = WC_Tax::calc_shipping_tax($amount, WC_Tax::get_shipping_tax_rates($cart[$cost_key]['data']->get_tax_class()));
                         // Sum the item taxes
                         foreach (array_keys($taxes + $item_taxes) as $key) {
                             $taxes[$key] = (isset($item_taxes[$key]) ? $item_taxes[$key] : 0) + (isset($taxes[$key]) ? $taxes[$key] : 0);
                         }
                     }
                     // Add any cost for the order - order costs are in the key 'order'
                     if (isset($args['cost']['order'])) {
                         $item_taxes = WC_Tax::calc_shipping_tax($args['cost']['order'], WC_Tax::get_shipping_tax_rates());
                         // Sum the item taxes
                         foreach (array_keys($taxes + $item_taxes) as $key) {
                             $taxes[$key] = (isset($item_taxes[$key]) ? $item_taxes[$key] : 0) + (isset($taxes[$key]) ? $taxes[$key] : 0);
                         }
                     }
                 }
                 break;
             default:
                 $taxes = WC_Tax::calc_shipping_tax($total_cost, WC_Tax::get_shipping_tax_rates());
                 break;
         }
     }
     $this->rates[] = new WC_Shipping_Rate($args['id'], $args['label'], $total_cost, $taxes, $this->id);
 }
コード例 #11
0
 /**
  * Get the highest hierarchy role for a user
  *
  * @param int $userid ID of the user to get the role for
  * @return bool|string User role name or false if the user doesn't exist
  */
 public static function update_product_pricing($product, $args)
 {
     $product = get_product($product);
     if (!$product) {
         return;
     }
     if ($product->is_type('variable', 'grouped')) {
         return;
     }
     $args = wp_parse_args($args, array('regular_price' => $product->get_regular_price(), 'sale_price' => $product->get_sale_price(), 'sale_price_dates_from' => $product->sale_price_dates_from, 'sale_price_dates_to' => $product->sale_price_dates_to));
     $regular_price = $args['regular_price'] === '' ? '' : wc_format_decimal($args['regular_price']);
     $sale_price = $args['sale_price'] === '' ? '' : wc_format_decimal($args['sale_price']);
     update_post_meta($product->id, '_regular_price', $regular_price);
     update_post_meta($product->id, '_sale_price', $sale_price);
     $date_from = $args['sale_price_dates_from'] ? $args['sale_price_dates_from'] : '';
     $date_to = $args['sale_price_dates_to'] ? $args['sale_price_dates_to'] : '';
     // Dates
     if ($date_from) {
         update_post_meta($product->id, '_sale_price_dates_from', strtotime($date_from));
     } else {
         update_post_meta($product->id, '_sale_price_dates_from', '');
     }
     if ($date_to) {
         update_post_meta($product->id, '_sale_price_dates_to', strtotime($date_to));
     } else {
         update_post_meta($product->id, '_sale_price_dates_to', '');
     }
     if ($date_to && !$date_from) {
         update_post_meta($product->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($product->id, '_price', wc_format_decimal($sale_price));
     } else {
         update_post_meta($product->id, '_price', $regular_price === '' ? '' : wc_format_decimal($regular_price));
     }
     if ($sale_price !== '' && $date_from && strtotime($date_from) < strtotime('NOW', current_time('timestamp'))) {
         update_post_meta($product->id, '_price', wc_format_decimal($sale_price));
     }
     if ($date_to && strtotime($date_to) < strtotime('NOW', current_time('timestamp'))) {
         update_post_meta($product->id, '_price', $regular_price === '' ? '' : wc_format_decimal($regular_price));
         update_post_meta($product->id, '_sale_price_dates_from', '');
         update_post_meta($product->id, '_sale_price_dates_to', '');
     }
 }
コード例 #12
0
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     $tendered = isset($_REQUEST['pos-cash-tendered']) ? wc_format_decimal($_REQUEST['pos-cash-tendered']) : 0;
     $tendered = abs((double) $tendered);
     $total = isset($_REQUEST['total']) ? $_REQUEST['total'] : 0;
     $total = abs((double) $total);
     if ($tendered !== 0) {
         // calculate change
         $change = $tendered - $total;
         // add order meta
         update_post_meta($order_id, '_pos_cash_amount_tendered', $tendered);
         update_post_meta($order_id, '_pos_cash_change', $change);
     }
     // payment complete
     $order->payment_complete();
     // Return thankyou redirect
     return array('result' => 'success');
 }
コード例 #13
0
/**
 * Generate coupons.
 *
 * Generate the coupons based on the $args arguments.
 *
 * @since 1.0.0
 * TODO
 */
function wccg_generate_coupons($number, $args = array())
{
    // Verify required values
    if (!isset($args['number_of_coupons'])) {
        return;
    }
    // TODO default args
    global $wpdb;
    $insert_coupon_ids = array();
    $wpdb->query('START TRANSACTION');
    // Query coupons
    $number_of_coupons = absint($number);
    for ($i = 0; $i < $number_of_coupons; $i++) {
        $coupon_code = wccg_get_random_coupon();
        // Insert coupon post
        $wpdb->query($wpdb->prepare("INSERT INTO {$wpdb->posts} SET\n\t\t\tpost_author=%d,\n\t\t\tpost_date=%s,\n\t\t\tpost_date_gmt=%s,\n\t\t\tpost_title=%s,\n\t\t\tpost_status='publish',\n\t\t\tcomment_status='closed',\n\t\t\tping_status='closed',\n\t\t\tpost_name=%s,\n\t\t\tpost_modified=%s,\n\t\t\tpost_modified_gmt=%s,\n\t\t\tpost_type='shop_coupon'\n\t\t\t", get_current_user_id(), current_time('mysql'), current_time('mysql', 1), sanitize_title($coupon_code), $coupon_code, current_time('mysql'), current_time('mysql', 1)));
        $insert_coupon_ids[] = $wpdb->insert_id;
        $coupon_id = $wpdb->insert_id;
        // Set GUID
        // 			$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET guid=%s WHERE ID=%d", get_permalink( $coupon_id ), $coupon_id ) ); // Slow
        $wpdb->query($wpdb->prepare("UPDATE {$wpdb->posts} SET guid=%s WHERE ID=%d", esc_url_raw(add_query_arg(array('post_type' => 'shop_coupon', 'p' => $coupon_id), home_url())), $coupon_id));
        // 10% faster -1 query per coupon
    }
    // Add/Replace data to array
    $meta_array = apply_filters('woocommerce_coupon_generator_coupon_meta_data', array('discount_type' => empty($args['discount_type']) ? 'fixed_cart' : wc_clean($args['discount_type']), 'coupon_amount' => wc_format_decimal($args['coupon_amount']), 'individual_use' => isset($args['individual_use']) ? 'yes' : 'no', 'product_ids' => implode(',', array_filter(array_map('intval', explode(',', $args['product_ids'])))), 'exclude_product_ids' => implode(',', array_filter(array_map('intval', explode(',', $args['exclude_product_ids'])))), 'usage_limit' => empty($args['usage_limit']) ? '' : absint($args['usage_limit']), 'usage_limit_per_user' => empty($args['usage_limit_per_user']) ? '' : absint($args['usage_limit_per_user']), 'limit_usage_to_x_items' => empty($args['limit_usage_to_x_items']) ? '' : absint($args['limit_usage_to_x_items']), 'expiry_date' => wc_clean($args['expiry_date']), 'free_shipping' => isset($args['free_shipping']) ? 'yes' : 'no', 'exclude_sale_items' => isset($args['exclude_sale_items']) ? 'yes' : 'no', 'product_categories' => isset($args['product_categories']) ? array_map('intval', $args['product_categories']) : array(), 'exclude_product_categories' => isset($args['exclude_product_categories']) ? array_map('intval', $args['exclude_product_categories']) : array(), 'minimum_amount' => wc_format_decimal($args['minimum_amount']), 'maximum_amount' => wc_format_decimal($args['maximum_amount']), 'customer_email' => array_filter(array_map('trim', explode(',', wc_clean($args['customer_email']))))), $coupon_id);
    $insert_meta_values = '';
    // Insert all coupons meta
    foreach ($meta_array as $key => $value) {
        foreach ($insert_coupon_ids as $coupon_id) {
            $insert_meta_values .= $wpdb->prepare('(%d, %s, %s)', $coupon_id, sanitize_title(wp_unslash($key)), maybe_serialize(wp_unslash($value)));
            $meta_array_keys = array_keys($meta_array);
            if ($key == end($meta_array_keys) && $coupon_id == end($insert_coupon_ids)) {
                $insert_meta_values .= ';';
            } else {
                $insert_meta_values .= ', ';
            }
        }
    }
    $wpdb->query("INSERT INTO {$wpdb->postmeta} (post_id, meta_key, meta_value) VALUES {$insert_meta_values}");
    $wpdb->query('COMMIT');
}
コード例 #14
0
 static function get_orders($untyped_array_of_orders)
 {
     $typed_array_of_products = array();
     foreach ($untyped_array_of_orders as $untyped_order) {
         $wc_order = wc_get_order($untyped_order->ID);
         $typed_order = new Matrix42_Order();
         $typed_order->id = $wc_order->id;
         $typed_order->created_at = $wc_order->order_date;
         $typed_order->updated_at = $wc_order->modified_date;
         $typed_order->completed_at = $wc_order->completed_date;
         $typed_order->status = $wc_order->get_status();
         $customer = get_user_by('id', $wc_order->customer_user);
         $typed_order->customer = array('id' => $customer->ID, 'email' => $customer->user_email, 'first_name' => $customer->user_firstname, 'last_name' => $customer->user_lastname, 'login_name' => $customer->user_login);
         $typed_order->order_url = $wc_order->get_view_order_url();
         foreach ($wc_order->get_items() as $item_id => $item) {
             $product = $wc_order->get_product_from_item($item);
             $typed_order->order_items[] = array('id' => $item_id, 'price' => wc_format_decimal($wc_order->get_item_total($item), 2), 'quantity' => (int) $item['qty'], 'name' => $item['name'], 'product_id' => isset($product->variation_id) ? $product->variation_id : $product->id, 'sku' => is_object($product) ? $product->get_sku() : null);
         }
         array_push($typed_array_of_products, $typed_order);
     }
     return $typed_array_of_products;
 }
 /**
  * Adds support for Customer/Order CSV Export by adding data for each
  * checkout add-on column header
  *
  * @since 1.1.0
  * @param array $order_data generated order data matching the column keys in the header
  * @param WC_Order $order order being exported
  * @param \WC_Customer_Order_CSV_Export_Generator $csv_generator instance
  * @return array
  */
 public function add_checkout_add_ons_to_csv_export_column_data($order_data, $order, $csv_generator)
 {
     $order_add_ons = wc_checkout_add_ons()->get_order_add_ons($order->id);
     $new_order_data = $add_on_data = array();
     foreach (wc_checkout_add_ons()->get_add_ons() as $add_on) {
         $value = '';
         $total = '';
         if (isset($order_add_ons[$add_on->id])) {
             $value = 'file' == $add_on->type ? wp_get_attachment_url($order_add_ons[$add_on->id]['value']) : $add_on->normalize_value($order_add_ons[$add_on->id]['normalized_value'], true);
             $total = wc_format_decimal($order_add_ons[$add_on->id]['total'], 2);
         }
         $add_on_data['checkout_add_on_' . $add_on->id] = $value;
         $add_on_data['checkout_add_on_total_' . $add_on->id] = $total;
     }
     if (isset($csv_generator->order_format) && ('default_one_row_per_item' == $csv_generator->order_format || 'legacy_one_row_per_item' == $csv_generator->order_format)) {
         foreach ($order_data as $data) {
             $new_order_data[] = array_merge((array) $data, $add_on_data);
         }
     } else {
         $new_order_data = array_merge($order_data, $add_on_data);
     }
     return $new_order_data;
 }
コード例 #16
0
 /**
  * Prepare a single coupon 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)
 {
     // Get the coupon code.
     $code = wc_get_coupon_code_by_id($post->ID);
     $coupon = new WC_Coupon($code);
     $data = array('id' => $coupon->get_id(), 'code' => $coupon->get_code(), 'date_created' => wc_rest_prepare_date_response($post->post_date_gmt), 'date_modified' => wc_rest_prepare_date_response($post->post_modified_gmt), 'discount_type' => $coupon->get_discount_type(), 'description' => $coupon->get_description(), 'amount' => wc_format_decimal($coupon->get_amount(), 2), 'expiry_date' => $coupon->get_expiry_date() ? wc_rest_prepare_date_response($coupon->get_expiry_date()) : null, 'usage_count' => (int) $coupon->get_usage_count(), 'individual_use' => $coupon->get_individual_use(), 'product_ids' => array_map('absint', (array) $coupon->get_product_ids()), 'exclude_product_ids' => array_map('absint', (array) $coupon->get_excluded_product_ids()), 'usage_limit' => $coupon->get_usage_limit() ? $coupon->get_usage_limit() : null, 'usage_limit_per_user' => $coupon->get_usage_limit_per_user() ? $coupon->get_usage_limit_per_user() : null, 'limit_usage_to_x_items' => (int) $coupon->get_limit_usage_to_x_items(), 'free_shipping' => $coupon->get_free_shipping(), 'product_categories' => array_map('absint', (array) $coupon->get_product_categories()), 'excluded_product_categories' => array_map('absint', (array) $coupon->get_excluded_product_categories()), 'exclude_sale_items' => $coupon->get_exclude_sale_items(), 'minimum_amount' => wc_format_decimal($coupon->get_minimum_amount(), 2), 'maximum_amount' => wc_format_decimal($coupon->get_maximum_amount(), 2), 'email_restrictions' => $coupon->get_email_restrictions(), 'used_by' => $coupon->get_used_by());
     $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($post));
     /**
      * 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);
 }
コード例 #17
0
 /**
  * Put posted addon data into an array
  *
  * @return array
  */
 private function get_posted_product_addons()
 {
     $product_addons = array();
     if (isset($_POST['product_addon_name'])) {
         $addon_name = $_POST['product_addon_name'];
         $addon_description = $_POST['product_addon_description'];
         $addon_type = $_POST['product_addon_type'];
         $addon_position = $_POST['product_addon_position'];
         $addon_required = isset($_POST['product_addon_required']) ? $_POST['product_addon_required'] : array();
         $addon_option_label = $_POST['product_addon_option_label'];
         $addon_option_price = $_POST['product_addon_option_price'];
         $addon_option_min = $_POST['product_addon_option_min'];
         $addon_option_max = $_POST['product_addon_option_max'];
         for ($i = 0; $i < sizeof($addon_name); $i++) {
             if (!isset($addon_name[$i]) || '' == $addon_name[$i]) {
                 continue;
             }
             $addon_options = array();
             $option_label = $addon_option_label[$i];
             $option_price = $addon_option_price[$i];
             $option_min = $addon_option_min[$i];
             $option_max = $addon_option_max[$i];
             for ($ii = 0; $ii < sizeof($option_label); $ii++) {
                 $label = sanitize_text_field(stripslashes($option_label[$ii]));
                 $price = wc_format_decimal(sanitize_text_field(stripslashes($option_price[$ii])));
                 $min = sanitize_text_field(stripslashes($option_min[$ii]));
                 $max = sanitize_text_field(stripslashes($option_max[$ii]));
                 $addon_options[] = array('label' => $label, 'price' => $price, 'min' => $min, 'max' => $max);
             }
             if (sizeof($addon_options) == 0) {
                 continue;
                 // Needs options
             }
             $data = array();
             $data['name'] = sanitize_text_field(stripslashes($addon_name[$i]));
             $data['description'] = wp_kses_post(stripslashes($addon_description[$i]));
             $data['type'] = sanitize_text_field(stripslashes($addon_type[$i]));
             $data['position'] = absint($addon_position[$i]);
             $data['options'] = $addon_options;
             $data['required'] = isset($addon_required[$i]) ? 1 : 0;
             // Add to array
             $product_addons[] = apply_filters('woocommerce_product_addons_save_data', $data, $i);
         }
     }
     if (!empty($_POST['import_product_addon'])) {
         $import_addons = maybe_unserialize(maybe_unserialize(stripslashes(trim($_POST['import_product_addon']))));
         if (is_array($import_addons) && sizeof($import_addons) > 0) {
             $valid = true;
             foreach ($import_addons as $addon) {
                 if (!isset($addon['name']) || !$addon['name']) {
                     $valid = false;
                 }
                 if (!isset($addon['description'])) {
                     $valid = false;
                 }
                 if (!isset($addon['type'])) {
                     $valid = false;
                 }
                 if (!isset($addon['position'])) {
                     $valid = false;
                 }
                 if (!isset($addon['options'])) {
                     $valid = false;
                 }
                 if (!isset($addon['required'])) {
                     $valid = false;
                 }
             }
             if ($valid) {
                 $product_addons = array_merge($product_addons, $import_addons);
             }
         }
     }
     uasort($product_addons, array($this, 'addons_cmp'));
     return $product_addons;
 }
 /**
  * Save shipping and tax options
  */
 public function wc_setup_shipping_taxes_save()
 {
     check_admin_referer('wc-setup');
     $woocommerce_calc_shipping = isset($_POST['woocommerce_calc_shipping']) ? 'yes' : 'no';
     $woocommerce_calc_taxes = isset($_POST['woocommerce_calc_taxes']) ? 'yes' : 'no';
     update_option('woocommerce_calc_shipping', $woocommerce_calc_shipping);
     update_option('woocommerce_calc_taxes', $woocommerce_calc_taxes);
     update_option('woocommerce_prices_include_tax', sanitize_text_field($_POST['woocommerce_prices_include_tax']));
     if ('yes' === $woocommerce_calc_shipping && !empty($_POST['shipping_cost_domestic'])) {
         // Delete existing settings if they exist
         delete_option('woocommerce_flat_rate_settings');
         // Init rate and settings
         $shipping_method = new WC_Shipping_Flat_Rate();
         $costs = array();
         $costs[] = wc_format_decimal(sanitize_text_field($_POST['shipping_cost_domestic']));
         if ($item_cost = sanitize_text_field($_POST['shipping_cost_domestic_item'])) {
             $costs[] = $item_cost . ' * [qty]';
         }
         $shipping_method->settings['cost'] = implode(' + ', array_filter($costs));
         $shipping_method->settings['enabled'] = 'yes';
         $shipping_method->settings['type'] = 'order';
         $shipping_method->settings['availability'] = 'specific';
         $shipping_method->settings['countries'] = array(WC()->countries->get_base_country());
         update_option($shipping_method->plugin_id . $shipping_method->id . '_settings', $shipping_method->settings);
     }
     if ('yes' === $woocommerce_calc_shipping && !empty($_POST['shipping_cost_international'])) {
         // Delete existing settings if they exist
         delete_option('woocommerce_international_delivery_settings');
         // Init rate and settings
         $shipping_method = new WC_Shipping_International_Delivery();
         $costs = array();
         $costs[] = wc_format_decimal(sanitize_text_field($_POST['shipping_cost_international']));
         if ($item_cost = sanitize_text_field($_POST['shipping_cost_international_item'])) {
             $costs[] = $item_cost . ' * [qty]';
         }
         $shipping_method->settings['cost'] = implode(' + ', array_filter($costs));
         $shipping_method->settings['enabled'] = 'yes';
         $shipping_method->settings['type'] = 'order';
         if (!empty($_POST['shipping_cost_domestic'])) {
             $shipping_method->settings['availability'] = 'excluding';
             $shipping_method->settings['countries'] = array(WC()->countries->get_base_country());
         }
         update_option($shipping_method->plugin_id . $shipping_method->id . '_settings', $shipping_method->settings);
     }
     if ('yes' === $woocommerce_calc_taxes && !empty($_POST['woocommerce_import_tax_rates'])) {
         $locale_info = (include WC()->plugin_path() . '/i18n/locale-info.php');
         $tax_rates = array();
         $country = WC()->countries->get_base_country();
         $state = WC()->countries->get_base_state();
         if (isset($locale_info[$country])) {
             if (isset($locale_info[$country]['tax_rates'][$state])) {
                 $tax_rates = $locale_info[$country]['tax_rates'][$state];
             } elseif (isset($locale_info[$country]['tax_rates'][''])) {
                 $tax_rates = $locale_info[$country]['tax_rates'][''];
             }
             if (isset($locale_info[$country]['tax_rates']['*'])) {
                 $tax_rates = array_merge($locale_info[$country]['tax_rates']['*'], $tax_rates);
             }
         }
         if ($tax_rates) {
             $loop = 0;
             foreach ($tax_rates as $rate) {
                 $tax_rate = array('tax_rate_country' => $rate['country'], 'tax_rate_state' => $rate['state'], 'tax_rate' => $rate['rate'], 'tax_rate_name' => $rate['name'], 'tax_rate_priority' => isset($rate['priority']) ? absint($rate['priority']) : 1, 'tax_rate_compound' => 0, 'tax_rate_shipping' => $rate['shipping'] ? 1 : 0, 'tax_rate_order' => $loop++, 'tax_rate_class' => '');
                 WC_Tax::_insert_tax_rate($tax_rate);
             }
         }
     }
     wp_redirect(esc_url_raw($this->get_next_step_link()));
     exit;
 }
コード例 #19
0
 /**
  * Return how much money this customer has spent.
  * @since 2.7.0
  * @return float
  */
 public function get_total_spent()
 {
     global $wpdb;
     $spent = $wpdb->get_var("SELECT SUM(meta2.meta_value)\n\t\t\tFROM {$wpdb->posts} as posts\n\t\t\tLEFT JOIN {$wpdb->postmeta} AS meta ON posts.ID = meta.post_id\n\t\t\tLEFT JOIN {$wpdb->postmeta} AS meta2 ON posts.ID = meta2.post_id\n\t\t\tWHERE   meta.meta_key       = '_customer_user'\n\t\t\tAND     meta.meta_value     = '" . esc_sql($this->get_id()) . "'\n\t\t\tAND     posts.post_type     = 'shop_order'\n\t\t\tAND     posts.post_status   IN ( 'wc-completed', 'wc-processing' )\n\t\t\tAND     meta2.meta_key      = '_order_total'\n\t\t");
     if (!$spent) {
         $spent = 0;
     }
     return wc_format_decimal($spent, 2);
 }
コード例 #20
0
 /**
  * Save product shipping data
  *
  * @since 2.2
  * @param int $id
  * @param array $data
  */
 private function save_product_shipping_data($id, $data)
 {
     if (isset($data['weight'])) {
         update_post_meta($id, '_weight', '' === $data['weight'] ? '' : wc_format_decimal($data['weight']));
     }
     // Product dimensions
     if (isset($data['dimensions'])) {
         // Height
         if (isset($data['dimensions']['height'])) {
             update_post_meta($id, '_height', '' === $data['dimensions']['height'] ? '' : wc_format_decimal($data['dimensions']['height']));
         }
         // Width
         if (isset($data['dimensions']['width'])) {
             update_post_meta($id, '_width', '' === $data['dimensions']['width'] ? '' : wc_format_decimal($data['dimensions']['width']));
         }
         // Length
         if (isset($data['dimensions']['length'])) {
             update_post_meta($id, '_length', '' === $data['dimensions']['length'] ? '' : wc_format_decimal($data['dimensions']['length']));
         }
     }
     // Virtual
     if (isset($data['virtual'])) {
         $virtual = true === $data['virtual'] ? 'yes' : 'no';
         if ('yes' == $virtual) {
             update_post_meta($id, '_weight', '');
             update_post_meta($id, '_length', '');
             update_post_meta($id, '_width', '');
             update_post_meta($id, '_height', '');
         }
     }
     // Shipping class
     if (isset($data['shipping_class'])) {
         wp_set_object_terms($id, wc_clean($data['shipping_class']), 'product_shipping_class');
     }
 }
コード例 #21
0
 /**
  * Calculate totals by looking at the contents of the order. Stores the totals and returns the orders final total.
  *
  * @since 2.2
  * @param  $and_taxes bool Calc taxes if true
  * @return float calculated grand total
  */
 public function calculate_totals($and_taxes = true)
 {
     $cart_subtotal = 0;
     $cart_total = 0;
     $fee_total = 0;
     $cart_subtotal_tax = 0;
     $cart_total_tax = 0;
     if ($and_taxes && wc_tax_enabled()) {
         $this->calculate_taxes();
     }
     // line items
     foreach ($this->get_items() as $item) {
         $cart_subtotal += wc_format_decimal(isset($item['line_subtotal']) ? $item['line_subtotal'] : 0);
         $cart_total += wc_format_decimal(isset($item['line_total']) ? $item['line_total'] : 0);
         $cart_subtotal_tax += wc_format_decimal(isset($item['line_subtotal_tax']) ? $item['line_subtotal_tax'] : 0);
         $cart_total_tax += wc_format_decimal(isset($item['line_tax']) ? $item['line_tax'] : 0);
     }
     $this->calculate_shipping();
     foreach ($this->get_fees() as $item) {
         $fee_total += $item['line_total'];
     }
     $this->set_total($cart_subtotal - $cart_total, 'cart_discount');
     $this->set_total($cart_subtotal_tax - $cart_total_tax, 'cart_discount_tax');
     $grand_total = round($cart_total + $fee_total + $this->get_total_shipping() + $this->get_cart_tax() + $this->get_shipping_tax(), wc_get_price_decimals());
     $this->set_total($grand_total, 'total');
     return $grand_total;
 }
コード例 #22
0
 /**
  * Get an individual variation's data
  *
  * @since 2.1
  * @param WC_Product $product
  * @return array
  */
 private function get_variation_data($product)
 {
     $variations = array();
     foreach ($product->get_children() as $child_id) {
         $variation = $product->get_child($child_id);
         if (!$variation->exists()) {
             continue;
         }
         $variations[] = array('id' => $variation->get_variation_id(), 'created_at' => $this->server->format_datetime($variation->get_post_data()->post_date_gmt), 'updated_at' => $this->server->format_datetime($variation->get_post_data()->post_modified_gmt), 'downloadable' => $variation->is_downloadable(), 'virtual' => $variation->is_virtual(), 'permalink' => $variation->get_permalink(), 'sku' => $variation->get_sku(), 'price' => wc_format_decimal($variation->get_price(), 2), 'regular_price' => wc_format_decimal($variation->get_regular_price(), 2), 'sale_price' => $variation->get_sale_price() ? wc_format_decimal($variation->get_sale_price(), 2) : null, 'taxable' => $variation->is_taxable(), 'tax_status' => $variation->get_tax_status(), 'tax_class' => $variation->get_tax_class(), 'stock_quantity' => (int) $variation->get_stock_quantity(), 'in_stock' => $variation->is_in_stock(), 'backordered' => $variation->is_on_backorder(), 'purchaseable' => $variation->is_purchasable(), 'visible' => $variation->variation_is_visible(), 'on_sale' => $variation->is_on_sale(), 'weight' => $variation->get_weight() ? wc_format_decimal($variation->get_weight(), 2) : null, 'dimensions' => array('length' => $variation->length, 'width' => $variation->width, 'height' => $variation->height, 'unit' => get_option('woocommerce_dimension_unit')), 'shipping_class' => $variation->get_shipping_class(), 'shipping_class_id' => 0 !== $variation->get_shipping_class_id() ? $variation->get_shipping_class_id() : null, 'image' => $this->get_images($variation), 'attributes' => $this->get_attributes($variation), 'downloads' => $this->get_downloads($variation), 'download_limit' => (int) $product->download_limit, 'download_expiry' => (int) $product->download_expiry);
     }
     return $variations;
 }
コード例 #23
0
 /**
  * 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);
 }
コード例 #24
0
 /**
  * Determines the value that the customer spent and the subtotal
  * displayed, used for things like coupon validation.
  *
  * Since the coupon lines are displayed based on the TAX DISPLAY value
  * of cart, this is used to determine the spend.
  *
  * If cart totals are shown including tax, use the subtotal.
  * If cart totals are shown excluding tax, use the subtotal ex tax
  * (tax is shown after coupons).
  *
  * @since 2.6.0
  * @return string
  */
 public function get_displayed_subtotal()
 {
     if ('incl' === $this->tax_display_cart) {
         return wc_format_decimal($this->subtotal);
     } elseif ('excl' === $this->tax_display_cart) {
         return wc_format_decimal($this->subtotal_ex_tax);
     }
 }
コード例 #25
0
 /**
  * Set total
  * @param string $value
  * @param string $deprecated Function used to set different totals based on this.
  * @throws WC_Data_Exception
  */
 public function set_total($value, $deprecated = '')
 {
     if ($deprecated) {
         _deprecated_argument('total_type', '2.7', 'Use dedicated total setter methods instead.');
         return $this->legacy_set_total($value, $deprecated);
     }
     $this->data['total'] = wc_format_decimal($value, wc_get_price_decimals());
 }
コード例 #26
0
 /**
  * Add a shipping rate. If taxes are not set they will be calculated based on cost.
  * @param array $args (default: array())
  */
 public function add_rate($args = array())
 {
     $args = wp_parse_args($args, array('id' => $this->get_rate_id(), 'label' => '', 'cost' => '0', 'taxes' => '', 'calc_tax' => 'per_order', 'meta_data' => array(), 'package' => false));
     // ID and label are required
     if (!$args['id'] || !$args['label']) {
         return;
     }
     // Total up the cost
     $total_cost = is_array($args['cost']) ? array_sum($args['cost']) : $args['cost'];
     $taxes = $args['taxes'];
     // Taxes - if not an array and not set to false, calc tax based on cost and passed calc_tax variable. This saves shipping methods having to do complex tax calculations.
     if (!is_array($taxes) && $taxes !== false && $total_cost > 0 && $this->is_taxable()) {
         $taxes = 'per_item' === $args['calc_tax'] ? $this->get_taxes_per_item($args['cost']) : WC_Tax::calc_shipping_tax($total_cost, WC_Tax::get_shipping_tax_rates());
     }
     // Round the total cost after taxes have been calculated.
     $total_cost = wc_format_decimal($total_cost, wc_get_price_decimals());
     // Create rate object
     $rate = new WC_Shipping_Rate($args['id'], $args['label'], $total_cost, $taxes, $this->id);
     if (!empty($args['meta_data'])) {
         foreach ($args['meta_data'] as $key => $value) {
             $rate->add_meta_data($key, $value);
         }
     }
     // Store package data
     if ($args['package']) {
         $items_in_package = array();
         foreach ($args['package']['contents'] as $item) {
             $product = $item['data'];
             $items_in_package[] = $product->get_title() . ' &times; ' . $item['quantity'];
         }
         $rate->add_meta_data(__('Items', 'woocommerce'), implode(', ', $items_in_package));
     }
     $this->rates[$args['id']] = $rate;
 }
コード例 #27
0
 /**
  * Get the customer for the given ID
  *
  * @since 2.1
  * @param int $id the customer ID
  * @param string $fields
  * @return array
  */
 public function get_customer($id, $fields = null)
 {
     global $wpdb;
     $id = $this->validate_request($id, 'customer', 'read');
     if (is_wp_error($id)) {
         return $id;
     }
     $customer = new WP_User($id);
     // get info about user's last order
     $last_order = $wpdb->get_row("SELECT id, post_date_gmt\n\t\t\t\t\t\tFROM {$wpdb->posts} AS posts\n\t\t\t\t\t\tLEFT JOIN {$wpdb->postmeta} AS meta on posts.ID = meta.post_id\n\t\t\t\t\t\tWHERE meta.meta_key = '_customer_user'\n\t\t\t\t\t\tAND   meta.meta_value = {$customer->ID}\n\t\t\t\t\t\tAND   posts.post_type = 'shop_order'\n\t\t\t\t\t\tAND   posts.post_status IN ( '" . implode("','", array_keys(wc_get_order_statuses())) . "' )\n\t\t\t\t\t");
     $customer_data = array('id' => $customer->ID, 'created_at' => $this->server->format_datetime($customer->user_registered), 'email' => $customer->user_email, 'first_name' => $customer->first_name, 'last_name' => $customer->last_name, 'username' => $customer->user_login, 'last_order_id' => is_object($last_order) ? $last_order->id : null, 'last_order_date' => is_object($last_order) ? $this->server->format_datetime($last_order->post_date_gmt) : null, 'orders_count' => (int) $customer->_order_count, 'total_spent' => wc_format_decimal($customer->_money_spent, 2), 'avatar_url' => $this->get_avatar_url($customer->customer_email), 'billing_address' => array('first_name' => $customer->billing_first_name, 'last_name' => $customer->billing_last_name, 'company' => $customer->billing_company, 'address_1' => $customer->billing_address_1, 'address_2' => $customer->billing_address_2, 'city' => $customer->billing_city, 'state' => $customer->billing_state, 'postcode' => $customer->billing_postcode, 'country' => $customer->billing_country, 'email' => $customer->billing_email, 'phone' => $customer->billing_phone), 'shipping_address' => array('first_name' => $customer->shipping_first_name, 'last_name' => $customer->shipping_last_name, 'company' => $customer->shipping_company, 'address_1' => $customer->shipping_address_1, 'address_2' => $customer->shipping_address_2, 'city' => $customer->shipping_city, 'state' => $customer->shipping_state, 'postcode' => $customer->shipping_postcode, 'country' => $customer->shipping_country));
     return array('customer' => apply_filters('woocommerce_api_customer_response', $customer_data, $customer, $fields, $this->server));
 }
コード例 #28
0
 /**
  * Ensure coupon amount is valid or throw exception.
  *
  * @throws Exception
  */
 private function validate_maximum_amount()
 {
     if ($this->maximum_amount > 0 && wc_format_decimal($this->maximum_amount) < wc_format_decimal(WC()->cart->subtotal)) {
         throw new Exception(self::E_WC_COUPON_MAX_SPEND_LIMIT_MET);
     }
 }
コード例 #29
0
 /**
  * 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);
 }
コード例 #30
-1
 /**
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     $cashback = isset($_POST['pos-cashback']) ? wc_format_decimal($_POST['pos-cashback']) : 0;
     if ($cashback !== 0) {
         // add order meta
         update_post_meta($order_id, '_pos_card_cashback', $cashback);
         // add cashback as fee line item
         // TODO: this should be handled by $order->add_fee after WC 2.2
         $item_id = wc_add_order_item($order_id, array('order_item_name' => __('Cashback', 'woocommerce-pos'), 'order_item_type' => 'fee'));
         if ($item_id) {
             wc_add_order_item_meta($item_id, '_line_total', $cashback);
             wc_add_order_item_meta($item_id, '_line_tax', 0);
             wc_add_order_item_meta($item_id, '_line_subtotal', $cashback);
             wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
             wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
         }
         // update the order total to include fee
         $order_total = get_post_meta($order_id, '_order_total', true);
         $order_total += $cashback;
         update_post_meta($order_id, '_order_total', $order_total);
     }
     // payment complete
     $order->payment_complete();
     // success
     return array('result' => 'success');
 }