Main/WordPress Fullstack/Blueprints/WooCommerce/Custom Shipping Method with Pickup Points & Interactive Map Integration
Back to «WooCommerce» cards
WooCommerce(ТЗ 40 из 54)
Spec: Custom Shipping Method with Pickup Points & Interactive Map Integration
WooCommerce5 шагов • +25 XP

Spec: Custom Shipping Method with Pickup Points & Interactive Map Integration

Engineering bespoke shipping methods: extending WC_Shipping_Method, dynamic rate calculation, integration with pickup point network API, Leaflet/Mapbox modal map selector, and storing chosen pickup point in order metadata.

~14 ч работыУровень: MiddleWC_Shipping_MethodWC_Shipping_RateLeaflet / OpenStreetMapCheckout Modal APIHPOS Shipping MetaREST API Courier Integration
+5 XP за шаг
Выполнено 0 из 5 шагов (0%)
Трудозатраты~14 рабочих часов
Фриланс вилка~$630 – $1,050 (€560 – €980)
Оценка веб-студии~$1,330 – $2,240 (€1260 – €2100)

ТЗ заказчика (исходный бриф):

We want a custom shipping option 'Pickup Point Locker'. Customers should see an interactive map at checkout, search by postal code, pick a locker location, and have the chosen locker address saved with the order.
Ключевые требования:
  • •Custom shipping method class extending WC_Shipping_Method registered via woocommerce_shipping_methods
  • •Dynamic shipping fee calculation based on cart weight and delivery zone
  • •Interactive map popup (Leaflet / OpenStreetMap) displaying nearby pickup lockers
  • •Validation ensuring pickup point is selected before order submission
  • •Store pickup locker ID, address, and operating hours in order meta
Ограничения проекта:
  • •Zero commercial shipping plugins with monthly subscriptions
  • •Free OpenStreetMap / Leaflet tile provider without costly Google Maps API billing
  • •Support both classic and block checkout
Критерии приёмки (KPI):
  • Interactive map loads in < 300ms
  • 100% of locker pickup orders contain valid locker IDs
  • Zero shipping rate calculation errors during checkout

Конфигурация блупринта под условия проекта

Выберите архитектуру и стек — шаги роадмапа, структура файлов и примеры кода переключатся автоматически:

Пошаговое практическое руководство по ТЗ

Подробный разбор архитектуры, код реализации и советы эксперта по каждому этапу:

1
Этап 1 из 5

Step 1: Custom shipping class extending WC_Shipping_Method

~50 минСредний

Практическое руководство:

Create WC_Shipping_Custom_Pickup class. Define id, method_title, method_description, and supports. Hook into 'woocommerce_shipping_init' and register via 'woocommerce_shipping_methods' filter.

План и контрольные точки реализации:
1Унаследовать класс от WC_Shipping_Method
2Определить поля init_form_fields() для настройки тарифов
3Реализовать метод calculate_shipping с динамическим расчетом стоимости
Важные технические нюансы и подводные камни:

Implement init_form_fields() so shipping cost, free shipping threshold, and API keys are configurable in WooCommerce settings.

Совет эксперта (Best Practice):

Округление веса в большую сторону: Большинство курьерских служб тарифицируют вес с округлением вверх до целого килограмма (ceil($total_weight)). Учитывайте это при калькуляции. (Важно: Если у товара не указан вес в админке, $product->get_weight() вернет пустую строку — обязательно приводите к (float).)

Ожидаемый артефакт этапа:

Полноценный метод доставки в зонах доставки WooCommerce.

PHP
<?php
declare(strict_types=1);

if (!defined('ABSPATH')) exit;

class WC_Shipping_Pvz extends \WC_Shipping_Method {
    public function __construct(int $instance_id = 0) {
        $this->id                 = 'pvz_shipping';
        $this->instance_id        = $instance_id;
        $this->method_title       = __('Доставка в ПВЗ (Самовывоз)', 'agenticlab');
        $this->method_description = __('Доставка до пункта выдачи с динамическим расчетом по весу и картой.', 'agenticlab');
        $this->supports           = ['shipping-zones', 'instance-settings'];

        $this->init();
    }

    public function init(): void {
        $this->init_form_fields();
        $this->init_settings();

        $this->title = $this->get_option('title', 'Самовывоз из ПВЗ');
        $this->enabled = $this->get_option('enabled', 'yes');

        add_action('woocommerce_update_options_shipping_' . $this->id, [$this, 'process_admin_options']);
    }

    public function init_form_fields(): void {
        $this->form_fields = [
            'enabled' => [
                'title'   => __('Включить', 'agenticlab'),
                'type'    => 'checkbox',
                'default' => 'yes',
            ],
            'title' => [
                'title'   => __('Название на чекауте', 'agenticlab'),
                'type'    => 'text',
                'default' => __('Пункт выдачи заказов (ПВЗ)', 'agenticlab'),
            ],
            'base_cost' => [
                'title'   => __('Базовая стоимость ($)', 'agenticlab'),
                'type'    => 'price',
                'default' => '250',
            ],
            'cost_per_kg' => [
                'title'   => __('Доплата за каждый 1 кг ($)', 'agenticlab'),
                'type'    => 'price',
                'default' => '50',
            ],
        ];
    }

    public function calculate_shipping($package = []): void {
        $base_cost = (float) $this->get_option('base_cost', 250);
        $cost_per_kg = (float) $this->get_option('cost_per_kg', 50);

        $total_weight = 0.0;
        foreach ($package['contents'] as $item) {
            /** @var \WC_Product $product */
            $product = $item['data'];
            $weight = (float) $product->get_weight();
            $total_weight += ($weight * (int) $item['quantity']);
        }

        $final_cost = $base_cost + ($total_weight * $cost_per_kg);

        $this->add_rate([
            'id'        => $this->get_rate_id(),
            'label'     => $this->title,
            'cost'      => $final_cost,
            'package'   => $package,
        ]);
    }
}

add_filter('woocommerce_shipping_methods', function ($methods) {
    $methods['pvz_shipping'] = 'WC_Shipping_Pvz';
    return $methods;
});
2
Этап 2 из 5

Step 2: Dynamic rate calculation & condition evaluation

~60 минСложный
3
Этап 3 из 5

Step 3: Interactive Leaflet map & pickup points API integration

~35 минСредний
4
Этап 4 из 5

Step 4: Checkout validation & hidden fields binding

~40 минСредний
5
Этап 5 из 5

Step 5: Order meta persistence & notification display

~30 минЛегкий

Типичные грабли на этом ТЗ

2 антипаттерна

Инструменты экосистемы Fullstack AI Lab для этого ТЗ

Интеграция