Creating a custom API shipping method for WooCommerce involves implementing a custom shipping method class and leveraging WooCommerce’s hooks to integrate it. This process typically includes defining a new shipping method, calculating rates dynamically, and providing tracking data via an API. Below is a step-by-step guide to help you achieve this:
1. Set Up Your Plugin
Create a custom plugin for this functionality. In your WordPress plugin directory, create a new folder, e.g., custom-shipping-method, and a PHP file, e.g., custom-shipping-method.php.
<?php
/**
* Plugin Name: Custom Shipping Method
* Description: Adds a custom shipping method with API integration for rates and tracking.
* Version: 1.0
* Author: Your Name
*/
// Exit if accessed directly.
if (!defined('ABSPATH')) {
exit;
}
// Include the custom shipping method class.
require_once plugin_dir_path(__FILE__) . 'includes/class-custom-shipping-method.php';
// Register the custom shipping method.
function register_custom_shipping_method($methods) {
$methods['custom_shipping'] = 'WC_Custom_Shipping_Method';
return $methods;
}
add_filter('woocommerce_shipping_methods', 'register_custom_shipping_method');
// Initialize the shipping method.
function init_custom_shipping_method() {
if (!class_exists('WC_Shipping_Method')) {
return;
}
include_once plugin_dir_path(__FILE__) . 'includes/class-custom-shipping-method.php';
}
add_action('woocommerce_shipping_init', 'init_custom_shipping_method');
2. Define Your Custom Shipping Method
Create a file includes/class-custom-shipping-method.php and define your custom shipping method class.
<?php
class WC_Custom_Shipping_Method extends WC_Shipping_Method {
public function __construct() {
$this->id = 'custom_shipping';
$this->method_title = __('Custom Shipping', 'woocommerce');
$this->method_description = __('Custom shipping method with API integration.', 'woocommerce');
$this->enabled = 'yes'; // Enable the method.
$this->title = __('Custom Shipping', 'woocommerce'); // Method title shown to users.
$this->init();
}
// Initialize settings.
public function init() {
$this->init_form_fields();
$this->init_settings();
$this->title = $this->get_option('title');
$this->enabled = $this->get_option('enabled');
add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_options']);
}
// Define settings fields.
public function init_form_fields() {
$this->form_fields = [
'enabled' => [
'title' => __('Enable/Disable', 'woocommerce'),
'type' => 'checkbox',
'description' => __('Enable this shipping method.', 'woocommerce'),
'default' => 'yes',
],
'title' => [
'title' => __('Title', 'woocommerce'),
'type' => 'text',
'description' => __('Title shown during checkout.', 'woocommerce'),
'default' => __('Custom Shipping', 'woocommerce'),
],
];
}
// Calculate shipping rates.
public function calculate_shipping($package = []) {
$rate = [
'id' => $this->id,
'label' => $this->title,
'cost' => 10.00, // Replace with dynamic rate calculation via API.
'calc_tax' => 'per_item',
];
$this->add_rate($rate);
}
}
3. Fetch Shipping Rates via API
To dynamically fetch rates, modify the calculate_shipping method to call an external API.
public function calculate_shipping($package = []) {
$response = wp_remote_get('https://api.example.com/shipping-rates', [
'body' => json_encode($package),
'headers' => ['Content-Type' => 'application/json'],
]);
if (is_wp_error($response)) {
return;
}
$data = json_decode(wp_remote_retrieve_body($response), true);
if (!empty($data['rates'])) {
foreach ($data['rates'] as $rate) {
$this->add_rate([
'id' => $this->id . '_' . $rate['id'],
'label' => $rate['label'],
'cost' => $rate['cost'],
'calc_tax' => 'per_item',
]);
}
}
}
4. Provide Tracking Information
You can add a custom endpoint to provide tracking data.
In your main plugin file:
add_action('rest_api_init', function () {
register_rest_route('custom-shipping/v1', '/tracking/(?P<order_id>\d+)', [
'methods' => 'GET',
'callback' => 'get_tracking_info',
'permission_callback' => '__return_true',
]);
});
function get_tracking_info($data) {
$order_id = $data['order_id'];
$order = wc_get_order($order_id);
if (!$order) {
return new WP_Error('invalid_order', 'Invalid order ID', ['status' => 404]);
}
$tracking_info = [
'order_id' => $order_id,
'tracking_number' => get_post_meta($order_id, '_tracking_number', true),
'carrier' => get_post_meta($order_id, '_tracking_carrier', true),
'status' => 'In Transit', // Fetch status dynamically from an API if needed.
];
return $tracking_info;
}
5. Add Tracking Data to Orders
You can extend the order meta to include tracking details when adding or editing orders. Use add_post_meta or update WooCommerce hooks to save tracking data.
6. Test Your Implementation
Ensure everything works correctly:
- Test rate calculations.
- Verify the REST API endpoint for tracking.
- Check for compatibility with WooCommerce updates.
This setup provides a basic framework to create a custom shipping method with API-driven rates and tracking information. Expand and refine it based on your specific requirements.
