Skip to content

Instantly share code, notes, and snippets.

@bahiirwa
Created October 29, 2016 06:23
Show Gist options
  • Save bahiirwa/989e4f60a4acdd2056d5fd33f372e281 to your computer and use it in GitHub Desktop.
Save bahiirwa/989e4f60a4acdd2056d5fd33f372e281 to your computer and use it in GitHub Desktop.
Creating a woocommerce shipping method based on total number of cart items.
<?php
function your_shipping_method_init() {
if ( ! class_exists( 'WC_Your_Shipping_Method' ) ) {
class WC_Your_Shipping_Method extends WC_Shipping_Method {
/*----------------------------------------------------------------
Constructor for your shipping class
----------------------------------------------------------------*/
public function __construct() {
$this->id = 'your_shipping_method'; // Id for your shipping method. Should be uunique.
$this->method_title = __( 'Your Shipping Method' ); // Title shown in admin
$this->method_description = __( 'Description of your shipping method' ); // Description shown in admin
$this->enabled = "yes"; // This can be added as an setting but for this example its forced enabled
$this->title = "My Shipping Method"; // This can be added as an setting but for this example its forced.
$this->init();
}
/*----------------------------------------------------------------
Init your settings
----------------------------------------------------------------*/
function init() {
// Load the settings API
$this->init_form_fields(); // This is part of the settings API. Override the method to add your own settings
$this->init_settings(); // This is part of the settings API. Loads settings you previously init.
// Save settings in admin if you have any defined
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
/*----------------------------------------------------------------
calculate_shipping function.
----------------------------------------------------------------*/
public function calculate_shipping( $package ) {
global $woocommerce;
$carttotal = $woocommerce->cart->cart_contents_count;
/*
1-5 packs 5,000
6-10 packs 10,000
11-15 packs 15,000
16-20 packs 20,000
*/
if($carttotal > 20){
$cost = 0;//Free delivery for above 20 packs
}else if($carttotal >= 16 && $carttotal <= 20){
$cost = 20000;
}else if($carttotal >= 11 && $carttotal <= 15){
$cost = 15000;
}else if($carttotal >= 6 && $carttotal <= 10){
$cost = 10000;
}else if($carttotal <= 5 && $carttotal >= 1){
$cost = 5000;
}
$rate = array(
'id' => $this->id,
'label' => 'Shipping',
'cost' => $cost,
);
// Register the rate
$this->add_rate( $rate );
}
}
}
}
add_action( 'woocommerce_shipping_init', 'your_shipping_method_init' );
function add_your_shipping_method( $methods ) {
$methods['your_shipping_method'] = 'WC_Your_Shipping_Method';
return $methods;
}
add_filter( 'woocommerce_shipping_methods', 'add_your_shipping_method' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment