Thêm order bằng code trong WooCommerce

Cập nhật lần cuối vào

WooCommerce là plugin giúp bạn tạo trang shop bán hàng trực tuyến, cho đến thời điểm hiện tại thì plugin này được sử dụng rất nhiều trên toàn cầu. Nếu bạn đang làm trang shop với WooCommerce và bạn muốn thêm order bằng code thay vì thông qua shopping cart thì bài viết này mình sẽ hướng dẫn cho bạn cách thực hiện nó.

Plugin WooCommerce 2.5.5

Để tạo order bằng code thì đương nhiên là bạn phải biết code PHP và code WordPress. Bạn sử dụng hàm wc_create_order để làm việc này.

function hocwp_wc_insert_order($data) {
    $post_id = hocwp_get_value_by_key($data, 'post_id');
    if(hocwp_id_number_valid($post_id)) {
        $post = get_post($post_id);
        if(is_a($post, 'WP_Post') && 'product' == $post->post_type) {
            $product = wc_get_product($post_id);
            $variable_product = new WC_Product_Variable($product);
            $variations = $variable_product->get_available_variations();
            $variation_args = array();
            $variation_id = null;
            foreach($variations as $variation) {
                $variation_id = $variation['variation_id'];
                $variation_args['variation'] = $variation['attributes'];
            }
            $name = hocwp_get_value_by_key($data, 'name');
            $phone = hocwp_get_value_by_key($data, 'phone');
            $email = hocwp_get_value_by_key($data, 'email');
            $address = hocwp_get_value_by_key($data, 'address');
            $message = hocwp_get_value_by_key($data, 'message');
            $name = hocwp_sanitize_first_and_last_name($name);
            $attributes = hocwp_get_value_by_key($data, 'attributes');
            $addresses = array(
                'first_name' => $name['first_name'],
                'last_name' => $name['last_name'],
                'email' => $email,
                'phone' => $phone,
                'address_1' => $address
            );
            $args = array(
                'customer_note' => $message,
                'created_via' => 'programmatically'
            );
            if(is_user_logged_in()) {
                $current = wp_get_current_user();
                $args['customer_id'] = $current->ID;
            }
            $order = wc_create_order($args);
            $gateway = WC_Payment_Gateways::instance();
            $gateways = $gateway->get_available_payment_gateways();
            if(hocwp_array_has_value($gateways)) {
                $gateway = current($gateways);
                $order->set_payment_method($gateway);
            }
            $order->set_address($addresses);
            $order->set_address($addresses, 'shipping');

            if(hocwp_array_has_value($attributes) && hocwp_id_number_valid($variation_id)) {
                foreach($attributes as $attribute) {
                    $attribute_name = hocwp_get_value_by_key($attribute, 'name');
                    $attribute_value = hocwp_get_value_by_key($attribute, 'value');
                    if(!empty($attribute_name) && !empty($attribute_value)) {
                        if(isset($variation_args['variation'][$attribute_name])) {
                            $variation_args['variation'][$attribute_name] = $attribute_value;
                        }
                    }
                }
                $variation_product = new WC_Product_Variation($variation_id);
                $order->add_product($variation_product, 1, $variation_args);
            } else {
                $order->add_product($product);
            }
            $order->record_product_sales();
            $order->calculate_totals();
            $order->payment_complete();
            return $order;
        }
    }
    return false;
}

Bạn mở tập tin functions.php của giao diện lên và thêm vào một hàm có nội dung như bên trên, chú ý là bạn phải thay đổi lại một số hàm bên mình viết sẵn bằng những hàm PHP khác hoặc hàm của bạn.

Ví dụ bây giờ bạn thêm một form đặt hàng tùy chỉnh, không thông qua giỏ hàng, không thông qua trang thanh toán và bạn sử dụng AJAX để làm việc này, trong nội dung của hàm xử lý AJAX trên server bạn viết như sau:

function hocwp_wc_order_item_ajax_callback() {
    $result = array(
        'success' => false,
        'html_data' => '<p class="alert alert-danger">Đã có lỗi xảy ra, xin vui lòng thử lại sau.</p>'
    );
    $post_id = hocwp_get_value_by_key($_POST, 'post_id');
    if(hocwp_id_number_valid($post_id)) {
        $post = get_post($post_id);
        if(is_a($post, 'WP_Post') && 'product' == $post->post_type) {
            $name = hocwp_get_value_by_key($_POST, 'name');
            $phone = hocwp_get_value_by_key($_POST, 'phone');
            $email = hocwp_get_value_by_key($_POST, 'email');
            $address = hocwp_get_value_by_key($_POST, 'address');
            $message = hocwp_get_value_by_key($_POST, 'message');
            $attributes = hocwp_get_value_by_key($_POST, 'attributes');
            $order = hocwp_wc_insert_order(array(
                'post_id' => $post_id,
                'name' => $name,
                'email' => $email,
                'phone' => $phone,
                'address' => $address,
                'message' => $message,
                'attributes' => $attributes
            ));
            if(false !== $order) {
                $result['success'] = true;
                $result['html_data'] = '<p class="alert alert-success">Đơn hàng của bạn đã được lưu thành công, chúng tôi sẽ liên hệ lại với bạn trong thời gian sớm nhất.</p>';
            }
        }
    }
    wp_send_json($result);
}
add_action('wp_ajax_hocwp_wc_order_item', 'hocwp_wc_order_item_ajax_callback');
add_action('wp_ajax_nopriv_hocwp_wc_order_item', 'hocwp_wc_order_item_ajax_callback');

Như vậy là bạn đã có thể thêm order tự động hoàn toàn bằng code, cái này phù hợp cho các bạn viết giao diện trang shop nâng cao, có tùy chỉnh nhiều, không thông qua các trang mặc định của WooCommerce. Chúc bạn thành công.