Last active
October 25, 2024 13:38
-
-
Save mikejolley/3b37b9cc19a774665f31 to your computer and use it in GitHub Desktop.
Example instance based shipping method
This file contains 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 | |
if ( ! defined( 'ABSPATH' ) ) { | |
exit; | |
} | |
/** | |
* Sample instance based method. | |
*/ | |
class WC_Shipping_Test_Method extends WC_Shipping_Method { | |
/** | |
* Constructor. The instance ID is passed to this. | |
*/ | |
public function __construct( $instance_id = 0 ) { | |
$this->id = 'test_method'; | |
$this->instance_id = absint( $instance_id ); | |
$this->method_title = __( 'Test Method' ); | |
$this->method_description = __( 'Some shipping method.' ); | |
$this->supports = array( | |
'shipping-zones', | |
'instance-settings', | |
); | |
$this->instance_form_fields = array( | |
'enabled' => array( | |
'title' => __( 'Enable/Disable' ), | |
'type' => 'checkbox', | |
'label' => __( 'Enable this shipping method' ), | |
'default' => 'yes', | |
), | |
'title' => array( | |
'title' => __( 'Method Title' ), | |
'type' => 'text', | |
'description' => __( 'This controls the title which the user sees during checkout.' ), | |
'default' => __( 'Test Method' ), | |
'desc_tip' => true | |
) | |
); | |
$this->enabled = $this->get_option( 'enabled' ); | |
$this->title = $this->get_option( 'title' ); | |
add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) ); | |
} | |
/** | |
* calculate_shipping function. | |
* @param array $package (default: array()) | |
*/ | |
public function calculate_shipping( $package = array() ) { | |
$this->add_rate( array( | |
'id' => $this->id . $this->instance_id, | |
'label' => $this->title, | |
'cost' => 100, | |
) ); | |
} | |
} |
@mikejolley this snippet is incredibly useful as a reference, thanks! 🙌
I think there's value adding the cost field as an example here too?
'cost' => array(
'title' => __( 'Cost' ),
'type' => 'text',
'placeholder' => '',
'description' => __( 'This controls the cost that is applied for this shipping method at checkout.' ),
'default' => '0',
'desc_tip' => true,
'sanitize_callback' => '',
),
One final suggestion is to add instance-settings-modal
to the supports
array, as this is a much nicer way to edit the method settings:
$this->supports = array(
'shipping-zones',
'instance-settings',
'instance-settings-modal'
);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@mikejolley Can you update this gist with example how to restrict this shipping method only to certain country. In non-instance based is easy, just set the countries and availability, but how its done in instance based?