-
Vadim TsukanovРазработчик
-
Дата публикации06.12.2021
-
КатегорияWordpress

Задача:Быстро сделать сайт на WooCommerce
Соберем большой пак сниппетов по woocommerce в одном месте
Добавление в корзину:
function add2Cart()
{
$productId = sanitize_text_field($_POST['productId']);
WC()->cart->add_to_cart( $productId );
$response = array(
'status' => 'success',
'message' => 'Товар добавлен в корзину'
);
echo json_encode($response);
wp_die();
}
где $productId - ID вариации
Удалить товар из корзины:
function deteleItemFromCart()
{
$productId = sanitize_text_field($_POST['pId']);
foreach ( WC()->cart->get_cart() as $cartItemKey => $cartItem ) {
if ( $cartItemKey == $productId ) {
$removed = WC()->cart->remove_cart_item( $cartItemKey );
}
}
if(!empty($removed)){
$result = array(
'status' => 'success',
'message' => 'Товар удален из корзины'
);
}else{
$result = array(
'status' => 'error',
'message' => 'что-то пошло не так'
);
}
echo json_encode($result);
wp_die();
}
Изменить количество товара в корзине:
function changeItemQty()
{
$productId = sanitize_text_field($_POST['pId']);
$newQuantity = sanitize_text_field($_POST['qty']);
foreach( WC()->cart->get_cart() as $cartItemKey => $cartItem ) {
if( $cartItemKey == $productId && $cartItem['quantity'] != $newQuantity ){
$changed = WC()->cart->set_quantity( $cartItemKey, $newQuantity );
}
}
if($changed){
$result = array(
'status' => 'success',
'message' => 'Количество товара в корзине изменено'
);
}else{
$result = array(
'status' => 'error',
'message' => 'что-то пошло не так, возможно нет в наличии'
);
}
echo json_encode($result);
wp_die();
}
Получить количество товара в корзине:
function getCartItemsNumber()
{
$result = array(
'number' => WC()->cart->get_cart_contents_count(),
'status' => 'success'
);
echo json_encode($result);
wp_die();
}
Изменить способ доставки:
function changeShippingMethod()
{
$result = array('status' => 'success');
$shippingName = sanitize_text_field($_POST['shippingName']);
$shippingMethod = sanitize_text_field($_POST['shippingMethod']);
if(!empty($shippingMethod)) {
if(!empty($shippingName)) {
WC()->session->set('chosen_shipping_methods', array($shippingMethod) );
WC()->cart->calculate_shipping();
WC()->cart->calculate_totals();
$currentShippingMethod = WC()->session->get( 'chosen_shipping_methods' );
if($currentShippingMethod[0] == $shippingMethod) {
$result['shipping_name'] = $shippingName;
} else {
$result['status'] = 'error';
$result['message'] = 'Can not change shipping method';
}
} else {
$result['status'] = 'error';
$result['message'] = 'Empty $shippingName';
}
} else {
$result['status'] = 'error';
$result['message'] = 'Empty $shippingMethod';
}
echo json_encode($result);
wp_die();
}
Создание заказа:
function makeOrder()
{
$result = array('status' => 'success');
global $woocommerce;
$customerName = esc_html($_POST['clientName']);
$customerSecondName = esc_html($_POST['clientSecondName']);
$customerCity = esc_html($_POST['city']);
$customerAddress = esc_html($_POST['address']);
$customerPostcode = esc_html($_POST['postcode']);
$customerEmail = esc_html($_POST['email']);
$customerPhone = esc_html($_POST['phone']);
$shippingComment = esc_html($_POST['shippingComment']);
$couponCode = sanitize_text_field($_POST['couponCode']);
// $products = esc_html($_POST['products']);
$shippingName = esc_html($_POST['shippingName']);
$shippingId = esc_html($_POST['shippingId']);
$shippingMethod = esc_html($_POST['shippingMethod']);
$shippingCost = esc_html($_POST['shippingCost']);
$search = array('-', '+', ' ', '(', ')');
$replace = array('', '', '', '', '', '');
$formatedCustomerPhone = str_replace($search, $replace, $customerPhone);
if(!empty($customerName)) {
$address['first_name'] = $address2['first_name'] = $customerName;
}
if(!empty($customerSecondName)) {
$address['last_name'] = $address2['last_name'] = $customerSecondName;
}
if(!empty($customerPhone)) {
$address['phone'] = $address2['phone'] = $customerPhone;
}
if(!empty($customerEmail)) {
$address['email'] = $address2['email'] = $customerEmail;
}
$address['country'] = 'RU';
$addr = '';
if(!empty($customerCity)) {
$address['city'] = $address2['city'] = $customerCity;
}
if(!empty($customerAddress)) {
$addr .= $customerAddress;
}
if(!empty($addr)) {
$address2['address_1'] = $customerAddress;
}
if(!empty($customerPostcode)) {
$address2['postcode'] = $customerPostcode;
}
$order = wc_create_order();
if(!empty($shippingComment)) {
$shippingComment = __($shippingComment);
$order->add_order_note( $shippingComment );
}
foreach (WC()->cart->get_cart() as $key => $basketItem) {
$product = wc_get_product($basketItem["variation_id"]);
$order->add_product( $product, $basketItem["quantity"]);
}
$order->set_address( $address, 'billing' );
$order->set_address( $address2, 'shipping' );
$payment_gateways = WC()->payment_gateways->payment_gateways();
$order->set_payment_method($payment_gateways['yookassa_epl']);
$order->update_status("pending", 'Imported order', TRUE);
$itemShip = new WC_Order_Item_Shipping();
$itemShip->set_method_title( $shippingName );
$itemShip->set_method_id( $shippingMethod.':'.$shippingId ); // set an existing Shipping method rate ID
$itemShip->set_total( $shippingCost );
$arResult = $order->add_item( $itemShip );
$coupons = WC()->cart->get_applied_coupons();
if(!empty($coupons)) {
foreach ($coupons as $coupon) {
$order->apply_coupon($coupon);
}
}
$order->calculate_totals();
if(!empty($order->id)) {
$redirectUrl = createPaymentByOrder($order->id);
if(!empty($redirectUrl)) {
$result['redirect_url'] = $redirectUrl;
foreach(WC()->cart->get_cart() as $key => $item) {
WC()->cart->remove_cart_item($key);
}
} else {
$result['status'] = 'error';
$result['message'] = '$redirectUrl is empty';
}
} else {
$result['status'] = 'error';
$result['message'] = 'Order not created';
}
echo json_encode($result);
wp_die();
}