WPCalibrate Distance Rate Shipping
Calculate WooCommerce shipping rates dynamically from driving-route distance between configurable origins and destinations using Google Routes API.
by WPCalibrate · github.com/zeeshanraza-official/wpcalibrate-distance-rate-shipping · website
Install
No release zip yet. The repository archive installs, but the folder name will carry the branch suffix and updates will not flow:
wp plugin install https://github.com/zeeshanraza-official/wpcalibrate-distance-rate-shipping/archive/refs/heads/main.zipWPCalibrate Distance Rate Shipping for WooCommerce
WPCalibrate Distance Rate Shipping is a production-grade, enterprise-ready WooCommerce shipping plugin that dynamically calculates customer shipping rates using actual road driving distance retrieved directly from the Google Maps Platform Routes API (Compute Routes v2).
Merchants can configure multiple independent shipping method instances per WooCommerce Shipping Zone, define custom dispatch locations, establish granular tiered distance pricing, enforce minimum/maximum caps, and protect site performance with a multi-tiered in-memory and transient route caching architecture.
Table of Contents
- About
- Key Features
- Architecture & Design
- Documentation & Setup Guide
- In-Dashboard Updates from GitHub
- Developer Hooks & Extensibility
- Security & Compliance
- Changelog
- Support
- License
About
The Problem with Traditional Shipping Calculation
Standard WooCommerce shipping methods rely on static flat rates, postcode tables, or simplified "as-the-crow-flies" straight-line radius models. These approaches fail in the real world:
- Geographic Barriers: Bodies of water, mountain ranges, circuitous highway layouts, or bridge detours make driving routes significantly longer than straight-line distance, leaving merchants undercharging and absorbing delivery losses.
- Overcharging Nearby Customers: Coarse shipping zones charge nearby customers the same rate as remote addresses.
- Legacy Distance Matrix API: Many older plugins still use Google's deprecated Distance Matrix API, which lacks modern route calculation engines, field masking, and modern traffic controls.
The WPCalibrate Solution
WPCalibrate Distance Rate Shipping solves these challenges by connecting directly to the modern Google Maps Platform Routes API (Compute Routes v2) (https://routes.googleapis.com/directions/v2:computeRoutes). It evaluates actual driving routes and road distances between your physical dispatch origins and the customer's delivery destination.
With multi-tier caching, repeated checkouts, AJAX cart updates, and Store API requests never make redundant external API calls, keeping customer checkout instant and Google billing minimal.
Key Features
- Google Routes API Compute Routes v2 Integration:
Uses modern POST-based routing with explicit
X-Goog-FieldMaskheaders (routes.distanceMeters,routes.duration) for optimal network payloads and rapid response times. - Multi-Instance Isolation in WooCommerce Shipping Zones: Add multiple instances of Distance Rate Shipping inside the same shipping zone (e.g., Local Van Delivery, Standard Freight, Express Long-Haul) or across different geographic zones with completely isolated settings and instance IDs.
- Flexible Pricing Modes:
- Base + Distance Rate: Fixed base handling cost + rate per kilometer or mile.
- Tiered Distance Bands: Set custom pricing tiers based on distance intervals (e.g., 0–10 km = $10, 10–25 km = $20, 25+ km = $35).
- Distance Band Calculation Modes: Choose between Fixed Price per Band or Per-Unit Rate within Band.
- Dynamic Cost Safeguards:
- Minimum & Maximum Charge Caps: Ensure delivery fees never fall below fuel costs or exceed ceiling thresholds.
- Free Shipping Threshold: Grant automatic free shipping when the package subtotal exceeds a configurable limit.
- Dual Dispatch Origin Resolution:
- Store Base Address: Uses standard WooCommerce store address (WooCommerce > Settings > General).
- Custom Origin: Specify a dedicated warehouse, fulfillment hub, or store location per shipping method instance.
- Fine-Grained Eligibility Controls:
- Minimum and maximum driving distance cutoffs.
- Minimum and maximum cart subtotal requirements.
- Minimum and maximum total package weight restrictions.
- Minimum and maximum item quantity thresholds.
- Postal code allow-list and block-list matching (supports wildcard patterns like
902*).
- 4-Tier Route Caching Architecture:
- In-Memory Runtime Cache: Guarantees zero duplicate requests within the same PHP lifecycle.
- WordPress Transients: SHA-256 hashed route keys stored with configurable TTL (default: 24 hours).
- Negative Caching: Failed lookups are cached for 300 seconds to prevent hammering APIs during rate limits.
- Instant Global Cache Purge: Versioned salt increment flushes all cached distances site-wide instantly without database table lockups.
- Configurable Failure Policies: Gracefully choose whether to hide the shipping method or apply a fallback flat rate if road routing is impossible.
- WooCommerce HPOS & Blocks Compatible:
Fully declared compatibility for High-Performance Order Storage (
custom_order_tables) and Cart & Checkout Blocks (cart_checkout_blocks). - Comprehensive Overview Onboarding Tab: Dedicated administrative dashboard tab explaining setup steps, formula calculations, and eligibility rules.
- Sensitive Credential Protection:
API keys are automatically masked in the UI (
AIzaSy...XXXX) and permanently redacted from error notices and WooCommerce debug logs. - GitHub-Powered Dashboard Updates: Native update checks and 1-click upgrades directly within Dashboard > Updates and the WordPress Plugins screen.
Architecture & Design
wpcalibrate-distance-rate-shipping/
├── wpcalibrate-distance-rate-shipping.php # Main entry point & bootstrap
├── uninstall.php # Safe, opt-in data retention uninstaller
├── readme.txt # WordPress.org standard metadata
├── license.txt # GNU GPL-2.0-or-later license
├── branding/ # Official dark/light background adaptive icons
│ ├── icon-dark.png
│ └── icon-white.png
├── assets/ # Frontend and admin stylesheets/scripts
│ ├── css/admin.css
│ └── js/admin.js
├── languages/ # Translation template (POT)
│ └── wpcalibrate-distance-rate-shipping.pot
└── src/ # PSR-4 Autoloaded source code
├── Autoloader.php # Zero-dependency autoloader
├── Plugin.php # Lifecycle orchestrator
├── Admin/ # Admin dashboard controllers
│ ├── Assets.php
│ ├── Diagnostics.php
│ ├── Menu.php
│ ├── Notices.php
│ ├── Overview.php
│ ├── Settings.php
│ └── Support.php
├── Cache/ # Caching engine
│ └── RouteCache.php
├── Dependencies/ # WooCommerce & HPOS verification
│ └── WooCommerceDependency.php
├── Licensing/ # Licensing status management
│ ├── LicenseManager.php
│ └── LicenseProviderInterface.php
├── Provider/ # Distance provider contracts & implementations
│ ├── DistanceProviderInterface.php
│ ├── DistanceResult.php
│ ├── GoogleRoutesProvider.php
│ └── ProviderRegistry.php
├── Shipping/ # WooCommerce shipping method engine
│ ├── DistanceBandCalculator.php
│ ├── DistanceRateShippingMethod.php
│ ├── EligibilityEvaluator.php
│ ├── OriginDestinationResolver.php
│ ├── RateCalculator.php
│ └── ShippingMethodRegistrar.php
├── Support/ # Utility helpers
│ ├── Capabilities.php
│ ├── Logger.php
│ └── Units.php
└── Updater/ # GitHub auto-updater engine
└── GitHubUpdater.php
Documentation & Setup Guide
Prerequisites
- WordPress: 7.0 or higher (tested up to 7.1.2)
- WooCommerce: 8.0 or higher (tested up to 11.1.2)
- PHP: 8.2 or 8.3
- Google Cloud Platform: An active project with Routes API enabled and a linked billing account.
Installation
Option 1: WordPress Dashboard Upload (Recommended)
- Download
wpcalibrate-distance-rate-shipping-1.0.1.zipfrom the latest GitHub Release. - In WordPress Admin, navigate to Plugins > Add New Plugin.
- Click Upload Plugin at the top.
- Choose the downloaded ZIP file and click Install Now.
- Click Activate Plugin.
Option 2: FTP / SFTP Upload
- Unzip
wpcalibrate-distance-rate-shipping-1.0.1.zip. - Upload the
wpcalibrate-distance-rate-shippingdirectory to/wp-content/plugins/. - In WordPress Admin, navigate to Plugins and click Activate under WPCalibrate Distance Rate Shipping.
Step 1: Google Cloud Routes API Setup
- Log in to the Google Cloud Console.
- Create or select an existing project.
- Ensure a valid billing account is linked under Billing.
- Navigate to APIs & Services > Library, search for Routes API (
routes.googleapis.com), and click Enable. - Navigate to APIs & Services > Credentials and click Create Credentials > API Key.
- (Recommended) Under API Restrictions, restrict the key to Routes API.
- In WordPress Admin, go to WPCalibrate > Distance Rate Shipping > Distance Provider.
- Paste your API key into the Google Routes API Key field.
- Click Test Google Routes API Connection. A green success message will confirm that origin and destination routes compute successfully.
Step 2: Assign to WooCommerce Shipping Zones
- Navigate to WooCommerce > Settings > Shipping > Shipping Zones.
- Click into the zone you wish to configure (e.g., Domestic, Local State, or Everywhere).
- Click Add shipping method.
- Select WPCalibrate Distance Rate Shipping and click Continue.
- Click Edit under the newly added method to configure instance options.
Step 3: Dispatch Origin Selection
Inside the shipping method settings modal:
- Origin Type:
- Store Base Address: Uses the default address set under WooCommerce > Settings > General.
- Custom Origin Address: Allows you to enter a specific dispatch address, city, postcode, state, and country. Ideal for fulfillment centers, ghost kitchens, or multiple retail warehouses.
Step 4: Calculation Methods
Choose how customer delivery costs are computed:
Mode A: Base Charge + Distance Rate
Applies a flat base fee plus a fixed rate multiplied by the road driving distance.
- Formula:
Cost = Base Charge + (Distance × Rate per Unit) - Example:
$10 Base + (15 km × $1.50/km) = $32.50
Mode B: Tiered Distance Bands
Allows you to define granular distance intervals with individual rates.
- Boundary Rule: Minimum distance is inclusive (
min <= distance), Maximum distance is exclusive (distance < max). - Example Configuration:
0 to 5 km: $5.00 flat5 to 15 km: $12.00 flat15 to 30 km: $25.00 flat30 to [empty]: $50.00 flat (covers 30 km and above)
Safeguards:
- Minimum Cost: Delivery charge will never be less than this figure.
- Maximum Cost: Delivery charge will never exceed this ceiling.
- Free Shipping Subtotal: Bypasses calculations and returns $0.00 when order total qualifies.
Step 5: Package Eligibility Rules
Fine-tune when this shipping method appears:
- Min / Max Distance: Bypasses the method if customer is closer than
minor further thanmax. - Min / Max Subtotal: Restricts the method to qualifying cart totals.
- Min / Max Weight: Restricts the method based on package weight (useful for freight vs courier methods).
- Postcode Restrictions:
- Allowed Postcodes: Only customers matching these postal codes or wildcard patterns (e.g.
902*) see the method. - Blocked Postcodes: Addresses matching these postal codes are blocked.
- Allowed Postcodes: Only customers matching these postal codes or wildcard patterns (e.g.
Step 6: Cache Management & Invalidation
- In WordPress Admin, navigate to WPCalibrate > Distance Rate Shipping > Cache & Performance.
- Cache Expiration Time: Configure how long distance calculations are stored in WordPress transients (default: 86,400 seconds / 24 hours).
- Clear All Route Caches: Click to instantly increment the global cache version salt, invalidating all stored route lookups across the store immediately without slowing database performance.
In-Dashboard Updates from GitHub
WPCalibrate Distance Rate Shipping includes an integrated update listener that communicates with the official GitHub Releases API.
┌───────────────────────────────┐
│ WordPress Dashboard Updates │
└───────────────┬───────────────┘
│
Checks for Releases
▼
┌───────────────────────────────┐
│ GitHub Releases API (v1.0.1) │
└───────────────┬───────────────┘
│
New Version Available?
▼
┌───────────────────────────────┐
│ 1-Click In-Dashboard Update │
└───────────────────────────────┘
- When a new release tag or package is published to GitHub, WordPress automatically detects it during scheduled transient checks.
- An update notice appears on the Plugins screen and under Dashboard > Updates:
There is a new version of WPCalibrate Distance Rate Shipping available. View version details or update now.
- Clicking Update Now automatically downloads, unpacks, and activates the new version directly in your dashboard.
- To force an immediate update check, click Check Again under Dashboard > Updates.
Developer Hooks & Extensibility
Developers can customize behaviors, payloads, costs, and providers using standard WordPress filters and actions:
Filters
// 1. Filter calculated shipping cost before adding to package
add_filter( 'wpcalibrate_distance_rate_shipping_cost', function( float $cost, float $distance, array $package, \WPCalibrate\DistanceRateShipping\Shipping\DistanceRateShippingMethod $method ) {
// Apply 10% holiday surcharge
return $cost * 1.10;
}, 10, 4 );
// 2. Filter method eligibility
add_filter( 'wpcalibrate_distance_rate_shipping_is_eligible', function( bool $is_eligible, array $package, array $settings, \WPCalibrate\DistanceRateShipping\Shipping\DistanceRateShippingMethod $method ) {
// Custom VIP customer exemption
if ( current_user_can( 'vip_customer' ) ) {
return true;
}
return $is_eligible;
}, 10, 4 );
// 3. Filter Google Routes API request payload
add_filter( 'wpcalibrate_distance_rate_shipping_google_request_body', function( array $body, string $origin, string $destination ) {
// Add avoidance rules (e.g. avoid toll roads)
$body['routeModifiers'] = array(
'avoidTolls' => true,
);
return $body;
}, 10, 3 );
// 4. Register custom distance provider (e.g. OpenRouteService or Mapbox)
add_filter( 'wpcalibrate_distance_rate_shipping_providers', function( array $providers ) {
// $providers['mapbox'] = new MyCustomMapboxProvider();
return $providers;
} );
// 5. Override GitHub Updater repository owner or repository name
add_filter( 'wpcalibrate_drs_github_repo_owner', function( string $owner ) {
return 'your-organization';
} );
add_filter( 'wpcalibrate_drs_github_repo_name', function( string $repo ) {
return 'wpcalibrate-distance-rate-shipping';
} );
Security & Compliance
- Zero Sensitive Data in Frontend / Logs: Google API keys and credentials are never output in frontend HTML, script locals, or unmasked log entries.
- Automated Data Redaction:
Logger::mask_sensitive_data()strips keys matching sensitive names and detects Google API key regex patterns (AIza...). - Capability Verification: All administration endpoints and settings actions strictly require
manage_woocommerceormanage_options. - WordPress Nonces: All settings forms and AJAX test connection requests enforce cryptographic nonce validation.
- Opt-In Uninstall Policy: Deleting the plugin retains merchant settings by default. Data is only erased if Delete Data on Uninstall is explicitly enabled under WPCalibrate > Distance Rate Shipping > General.
Changelog
[1.0.1] - 2026-10-06
- Fixed: Admin Sidebar Branding Logo Overflow — constrained
#adminmenutop-level icon globally to 20x20px viaadmin_headhook to prevent oversized rendering across non-plugin WordPress admin screens. - Fixed: Added automatic branding icon adaptation for light WordPress admin color themes (
body.admin-color-light). - Added: Comprehensive Overview onboarding tab (
src/Admin/Overview.php) in plugin settings detailing setup steps, calculation formulas, eligibility conditions, and quick shortcuts. - Added: Integrated GitHub Auto-Updater (
src/Updater/GitHubUpdater.php) enabling 1-click in-dashboard updates from GitHub releases. - Added: Automated unit and integration tests (
MenuTest,UpdaterTest, andtest_overview_tab_rendering). 36/36 tests passing (100%). - Improved: Package build scripts and verification procedures.
[1.0.0] - 2026-10-05
- Initial Production Release.
- Native WooCommerce shipping method integration supporting multiple instances per Shipping Zone.
- Google Maps Platform Routes API Compute Routes v2 implementation.
- Base + Distance Rate, Tiered Distance Bands, Min/Max caps, and Free Shipping thresholds.
- Multi-tiered caching engine (Runtime memory, Transients, Negative cache, Versioned purge).
- Full compatibility with WooCommerce High-Performance Order Storage (HPOS) and Cart & Checkout Blocks.
- Shared WPCalibrate admin menu and diagnostic tools.
Support
Need assistance with setup, custom distance providers, or fleet pricing configuration?
- Direct Support Email: support@wpcalibrate.com
- WhatsApp Support: +447474795976
- Official Website: https://wpcalibrate.com
- Plugin Marketplace: https://marketplace.wpcalibrate.com/
License
This project is licensed under the GNU General Public License v2.0 or later — see the license.txt file for details.