Skip to content

Instantly share code, notes, and snippets.

@luizbills
Last active December 2, 2023 16:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luizbills/a7d1e3bc8f95beab0e15a9341272188c to your computer and use it in GitHub Desktop.
Save luizbills/a7d1e3bc8f95beab0e15a9341272188c to your computer and use it in GitHub Desktop.
Custom shipping method for WooCommerce (minimal boilerplate required)
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
// Hooks
add_action( 'plugins_loaded', 'yourprefix_include_shipping_method' );
add_action( 'woocommerce_shipping_methods', 'yourprefix_register_shipping_method' );
function yourprefix_include_shipping_method () {
include 'shipping-method.php';
}
function yourprefix_register_shipping_method ( $methods ) {
$methods['your-shipping-method-id'] = 'YourPrefix_Shipping_Method'; // full class name
return $methods;
}
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly.
}
class YourPrefix_Shipping_Method extends \WC_Shipping_Method {
public $id;
public $instance_id;
public $method_title;
public $method_description;
public $supports;
public $enabled;
public $title;
public function __construct( $instance_id = 0 ) {
$this->id = 'your-shipping-method-id';
$this->instance_id = absint( $instance_id );
$this->method_title = __( 'Your Shipping Method Name', 'textdomain' );
$this->method_description = __( 'Your Shipping Method Description', 'textdomain' );
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal',
);
$this->init();
}
function init() {
// Load the settings
$this->init_form_fields();
// Define user set variables
$this->title = $this->get_option( 'title' );
// Actions
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
}
function init_form_fields() {
$this->instance_form_fields = array(
'title' => array(
'title' => __( 'Title', 'textdomain' ),
'type' => 'text',
'description' => __( 'This controls the title which the user sees during checkout.', 'textdomain' ),
'desc_tip' => true,
'default' => $this->method_title,
),
/**
* Define your other settings
*/
);
}
public function calculate_shipping( $package = array() ) {
// Check if valid to be calculeted.
if ( '' === $package['destination']['postcode'] ) {
return;
}
// Do your shipping logic (e.g. request an API)
$this->add_rate(
array(
'label' => $this->title,
'cost' => 99,
'taxes' => false,
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment