You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

WooCommerce站点自定义Postcode查询配送区域功能咨询

How to Add a Custom Postcode Validation Form for WooCommerce Delivery Zones

Absolutely, you can build this custom postcode check feature—no need to copy the cart's shipping calculator. Let's break this down into simple, actionable steps:

1. Create the Frontend Postcode Form

First, add this HTML/CSS snippet to your homepage (or any page via a custom HTML block, theme template, or child theme file):

<div class="postcode-checker">
    <form id="postcode-validation-form" method="post">
        <label for="postcode">Enter your postcode:</label>
        <input type="text" id="postcode" name="postcode" required placeholder="e.g. SW1A 1AA">
        <button type="submit" name="check_postcode">Check Delivery</button>
    </form>
    <div id="delivery-message" class="delivery-message"></div>
</div>

<style>
.postcode-checker {
    max-width: 400px;
    margin: 2rem auto;
    padding: 1.5rem;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    text-align: center;
}
.postcode-checker label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 500;
}
.postcode-checker input {
    width: 100%;
    padding: 0.75rem;
    margin-bottom: 1rem;
    border: 1px solid #ddd;
    border-radius: 4px;
}
.postcode-checker button {
    padding: 0.75rem 1.5rem;
    background: #2d3748;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
.delivery-message.error {
    color: #dc2626;
    margin-top: 1rem;
    font-weight: 500;
}
</style>

2. Add PHP Validation Logic

Next, add this code to your theme's functions.php file (or a custom plugin, which is safer for theme updates):

add_action('template_redirect', 'validate_postcode_for_delivery');

function validate_postcode_for_delivery() {
    // Only run if the form was submitted
    if (!isset($_POST['check_postcode']) || empty($_POST['postcode'])) {
        return;
    }

    // Sanitize the input to avoid security issues
    $user_postcode = sanitize_text_field($_POST['postcode']);
    $delivery_available = false;

    // Make sure WooCommerce shipping functions are available
    if (!class_exists('WC_Shipping_Zones')) {
        wc_add_notice(__('WooCommerce is required for this feature.', 'woocommerce'), 'error');
        return;
    }

    // Get all active shipping zones in your store
    $shipping_zones = WC_Shipping_Zones::get_zones();

    // Loop through each zone to check the postcode
    foreach ($shipping_zones as $zone) {
        foreach ($zone['zone_locations'] as $location) {
            // Skip non-postcode location rules
            if ($location->type !== 'postcode') {
                continue;
            }

            // Validate the postcode against the zone's country and pattern
            if (WC_Validation::is_postcode_valid($user_postcode, $location->country) && 
                WC_Validation::postcode_match($location->code, $user_postcode)) {
                $delivery_available = true;
                break 2; // Exit both loops once a match is found
            }
        }
    }

    // Handle the result
    if ($delivery_available) {
        // Redirect to your Shop page (uses WooCommerce's default shop page)
        wp_redirect(get_permalink(woocommerce_get_page_id('shop')));
        exit;
    } else {
        // Store the error message to display on the frontend
        wc_add_notice(__('We do not deliver to this area', 'woocommerce'), 'error');
    }
}

To make the user experience smoother, add this JavaScript to display the error message directly below the form (instead of WooCommerce's default notice area):

document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('postcode-validation-form');
    const messageDiv = document.getElementById('delivery-message');

    // Check for any WooCommerce error notices and display them in our custom div
    const woocommerceNotice = document.querySelector('.woocommerce-error');
    if (woocommerceNotice) {
        messageDiv.textContent = woocommerceNotice.textContent.trim();
        messageDiv.classList.add('error');
        woocommerceNotice.remove(); // Hide the default notice if needed
    }

    // Add a loading state to the button during submission
    form.addEventListener('submit', function(e) {
        const submitButton = form.querySelector('button');
        submitButton.disabled = true;
        submitButton.textContent = 'Checking...';
    });
});

Key Notes

  • Security: We use sanitize_text_field to clean the user's input, which helps prevent malicious code from being submitted.
  • WooCommerce Compatibility: This uses WooCommerce's built-in validation functions (WC_Validation) to ensure accuracy with postcode formats across different countries.
  • Theme Safety: If you're using a parent theme, always add custom code to a child theme or a custom plugin to avoid losing changes when the theme updates.

内容的提问来源于stack exchange,提问作者devHensh

火山引擎 最新活动