-
-
Save farik92/a59dfeabaf6ba78c5d57ae441490a0c9 to your computer and use it in GitHub Desktop.
Програмное создание заказа в WooCommerce через Ajax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Создание заказа по кнопке "Заказать в один клик | |
| */ | |
| function roomble_ajax_create_order() { | |
| // Получить корзину | |
| $cart = WC()->cart; | |
| $phone = esc_attr( trim( $_REQUEST['phone'] ) ); | |
| $email = esc_attr( trim( $_REQUEST['email'] ) ); | |
| $name = esc_attr( trim( $_REQUEST['name'] ) ); | |
| $nonce = esc_attr( trim( $_REQUEST['nonce'] ) ); | |
| if( ! wp_verify_nonce( $nonce, 'woocommerce-cart' ) ) { | |
| wp_send_json_error('Не совпадает ключ безопасности. Обратитесь к разработчикам.'); | |
| } | |
| $address = [ | |
| 'first_name' => $name, | |
| 'email' => $email, | |
| 'phone' => $phone, | |
| 'country' => 'RU', | |
| ]; | |
| $order = wc_create_order(); | |
| // Информация о покупателе | |
| $order->set_address( $address, 'billing' ); | |
| $order->set_address( $address, 'shipping' ); | |
| // Товары из корзины | |
| foreach( $cart->get_cart() as $cart_item_key => $cart_item ) { | |
| $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); | |
| $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); | |
| $order->add_product( $_product, $cart_item['quantity'], [ | |
| 'variation' => $cart_item['variation'], | |
| 'totals' => [ | |
| 'subtotal' => $cart_item['line_subtotal'], | |
| 'subtotal_tax' => $cart_item['line_subtotal_tax'], | |
| 'total' => $cart_item['line_total'], | |
| 'tax' => $cart_item['line_tax'], | |
| 'tax_data' => $cart_item['line_tax_data'] | |
| ] | |
| ]); | |
| } | |
| // Добавить купоны | |
| foreach ( $cart->get_coupons() as $code => $coupon ) { | |
| $order->add_coupon( $code, $cart->get_coupon_discount_amount( $code ), $cart->get_coupon_discount_tax_amount( $code ) ); | |
| } | |
| $order->calculate_totals(); | |
| // Отправить письмо юзеру | |
| $mailer = WC()->mailer(); | |
| $email = $mailer->emails['WC_Email_Customer_Processing_Order']; | |
| $email->trigger( $order->id ); | |
| // Отправить письмо админу | |
| $email = $mailer->emails['WC_Email_New_Order']; | |
| $email->trigger( $order->id ); | |
| // Очистить корзину | |
| $cart->empty_cart(); | |
| wp_send_json_success( $order->id ); | |
| } | |
| add_action( 'wp_ajax_create_order', 'roomble_ajax_create_order' ); | |
| add_action( 'wp_ajax_nopriv_create_order', 'roomble_ajax_create_order' ); | |
| ?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment