/ Плагины / Пользовательский метод доставки

Пользовательский метод доставки

HIT

02.11.2019

2711

Создадим пользовательский метод доставки для Woocommerce 3.0.

Метод создадим в виде плагина.

<?php
 
/**
 * Plugin Name: Shop Custom Shipping Method
 * Plugin URI: 
 * Description: Custom Shipping Method for WooCommerce
 * Version: 1.0.0
 * Author: 
 * Author URI: 
 * License: GPL-3.0+
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 * Domain Path: 
 * Text Domain: 
 */
 
if ( ! defined( 'WPINC' ) ) { die; }
 
// Check if WooCommerce is active
if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
 
	add_action( 'woocommerce_shipping_init', 'econt_shipping_method' );
	function econt_shipping_method() {
	  if ( ! class_exists( 'WC_Econt_Shipping_Method' ) ) {
		class WC_Econt_Shipping_Method extends WC_Shipping_Method {
			
		public function __construct( $instance_id = 0 ) {
			$this->instance_id 	  = absint( $instance_id );
			$this->id                 = 'econt';//this is the id of our shipping method
			$this->method_title       = __( 'Доставка ТК', 'teame' );
			$this->method_description = __( 'Доставка товара транспортной компанией', 'teame' );
			//add to shipping zones list
			$this->supports = array(
				'shipping-zones',
				//'settings', //use this for separate settings page
				'instance-settings',
				'instance-settings-modal',
			);
			//make it always enabled
			$this->title = __( 'Доставка ТК', 'teame' );
			$this->enabled = 'yes';
			$this->init();
		}
		  
		function init() {
			// Load the settings API
			$this->init_form_fields();
			$this->init_settings();
			// Save settings in admin if you have any defined
			add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
		}
		  
		//Fields for the settings page
		function init_form_fields() {
			//fileds for the modal form from the Zones window
			$this->instance_form_fields = array(
				'title' => array(
					'title' => __( 'Название', 'teame' ),
					'type' => 'text',
					'description' => __( 'Доставка ТК', 'teame' ),
					'default' => __( 'Доставка товара транспортной компанией', 'teame' )
				),
				'cost' => array(
					'title' => __( 'Стоимость', 'teame' ),
					'type' => 'number',
					'description' => __( 'Стоимость доставки', 'teame' ),
					'default' => 500
				),
			);
			//$this->form_fields - use this with the same array as above for setting fields for separate settings page
		}
		  
		public function calculate_shipping( $package = array()) {
		//as we are using instances for the cost and the title we need to take those values drom the instance_settings
			$intance_settings =  $this->instance_settings;
			// Register the rate
			$this->add_rate( array(
				'id'      => $this->id,
				'label'   => $intance_settings['title'],
				'cost'    => $intance_settings['cost'],
				'package' => $package,
				'taxes'   => false,
			)
			);
		}
		  
		}
	  }
	  
	  //add your shipping method to WooCommers list of Shipping methods
	  add_filter( 'woocommerce_shipping_methods', 'add_econt_shipping_method' );
	  function add_econt_shipping_method( $methods ) {
		  $methods['econt'] = 'WC_Econt_Shipping_Method';
		  return $methods;
	  }
	}

}

Создадим для пользовательского метода уведомление при превышении веса (лимит установлен на 0):

function econt_validate_order( $posted )   {

	$packages = WC()->shipping->get_packages();
	$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
	
	if( is_array( $chosen_methods ) && in_array( 'econt', $chosen_methods ) ) {
		 
		foreach ( $packages as $i => $package ) {

			if ( $chosen_methods[$i] != "econt" ) { continue; } // Проверяем только пользовательский метод доставки
			
			// Получим общий вес заказа
			global $woocommerce;
			$total_weight = $woocommerce->cart->cart_contents_weight;
			
			// Определяем лиммит веса
			$weightLimit = 5;
			
			// Вычисляем разницу
			$difference = $total_weight - $weightLimit;
			
			// Получаем единицу измерения
			$unit = get_option('woocommerce_weight_unit');			

			if( $total_weight > $weightLimit ) {

				$message = sprintf( __( 'Вы превысили лимит по весу на %d %s', 'teame' ), $difference, $unit );
						 
				$messageType = "error";

				if( ! wc_has_notice( $message, $messageType ) ) {
					wc_add_notice( $message, $messageType );
				}
			}
		}       
	} 
}
 
add_action( 'woocommerce_review_order_before_cart_contents', 'econt_validate_order' , 10 );
add_action( 'woocommerce_after_checkout_validation', 'econt_validate_order' , 10 );	

т.е. если у нас будет в корзине хоть какой-то вес и выбран пользовательский метод доставки, то выведется предупреждение «Вы превысили лимит по весу» и не даст совершить заказ.

Стоимость доставки в зависимости от веса

В функции calculate_shipping( $package = array()) задается стоимость метода доставки. Стоимость доставки в зависимости от общего веса:

public function calculate_shipping( $package = array()) {
	$intance_settings =  $this->instance_settings;
	
	global $woocommerce;
	$total_weight = $woocommerce->cart->cart_contents_weight;
	
	$cost = $total_weight * 30; // 30 руб/кг
	
	// Register the rate
	$this->add_rate( array(
		'id'      => $this->id,
		'label'   => $intance_settings['title'],
		//'cost'    => $intance_settings['cost'],
		'cost'    => $cost,
		'package' => $package,
		'taxes'   => false,
	)
	);
	
}

Зависимость от того физическим или юридическим лицом является покупатель:

if( WC()->session->get( 'is_company' ) ){
	$cost = 320000;
} else {
	$cost = 7450;
}

Но для того чтобы стоимость доставки пересчитывалась динамически нужно прописать функцию:

// Ajax-обновление стоимости метода доставки
add_action('woocommerce_checkout_update_order_review', 'checkout_update_refresh_shipping_methods', 10, 1);
function checkout_update_refresh_shipping_methods( $post_data ) {
    $packages = WC()->cart->get_shipping_packages();
    foreach ($packages as $package_key => $package ) {
         WC()->session->set( 'shipping_for_package_' . $package_key, false ); // Or true
    }
}

Поделиться в соц. сетях:

  • Похожие записи
  • Комментарии
  • Вложения
Новинка (товар NEW полем)

Новинка (товар NEW полем)

Ранее были рассмотрены варианты добавления лэйбла New полуавтоматическим способом (последние созданные товары, либо по времени от текущего), либо назначением метки NEW. Здесь разберем как сделать данный функционал полем и какие Читать далее »

/
Виртуальный и Скачиваемый товар

Виртуальный и Скачиваемый товар

В интернет-магазине Woocommerce можно создавать Виртуальный и Скачиваемый товары. Разберемся как это выглядит и работает. Виртуальный товар Данная опция не меняет структуру товара. Если при оформлении в корзине только виртуальные Читать далее »

Хлебные крошки WC

Хлебные крошки WC

Хлебные крошки WC имеют свои особенности. Их невозможно заменить стандартными хлебными крошками, т.к. в них еще не предусмотрена система для иерархических таксономий. Выводим хлебные крошки Первым делом надо назначить хлебные Читать далее »

Добавить комментарий

Пока нет комментариев. Будь первым!

Пользовательский метод доставки
Вспомогательная информация
Рекомендации для васВспомогательная информацияOpttour.ru
Спасибо! Наш менеджер свяжется с Вами в течении 5 минут.