You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现WooCommerce产品配送标签自定义字段自动计算填充且保留管理员手动编辑权限?

Solution: Auto-populate Custom Shipping Fields with Calculated Values (Preserve Manual Edit)

Perfect, let's get this working for you. The goal is to auto-fill your custom Loading meters and Loading weight fields with calculated initial values, while still letting admins override them manually. Here's how to implement it step by step:

Key Logic

We'll calculate the initial values only when the fields are empty (no existing manual entry). When an admin opens a product edit page:

  1. Fetch the product's default length/height, convert them to meters (matching WooCommerce's dimension unit settings).
  2. Calculate Loading meters using your formula if no saved value exists.
  3. Calculate Loading weight from the (calculated or saved) Loading meters if no saved value exists.
  4. Render the fields with these calculated defaults, but let admins edit them freely—saved edits will persist.

Updated Code Snippets

1. Modified Field Rendering (with Auto-calculation)

Replace your existing woocommerce_product_options_shipping hook code with this:

add_action('woocommerce_product_options_shipping', function() {
    global $post;
    $product = wc_get_product($post->ID);
    
    // Get product's length and height (in WooCommerce's configured unit)
    $length = $product->get_length();
    $height = $product->get_height();
    
    // Convert dimensions to meters, based on store's unit setting
    $dimension_unit = get_option('woocommerce_dimension_unit');
    $length_in_m = 0;
    $height_in_m = 0;
    
    if ($length && $height) {
        switch($dimension_unit) {
            case 'cm':
                $length_in_m = $length / 100;
                $height_in_m = $height / 100;
                break;
            case 'mm':
                $length_in_m = $length / 1000;
                $height_in_m = $height / 1000;
                break;
            case 'in':
                $length_in_m = $length * 0.0254;
                $height_in_m = $height * 0.0254;
                break;
            case 'yd':
                $length_in_m = $length * 0.9144;
                $height_in_m = $height * 0.9144;
                break;
            default: // 'm' (meters)
                $length_in_m = floatval($length);
                $height_in_m = floatval($height);
                break;
        }
    }
    
    // Get saved loading meters, or calculate if empty
    $loading_meters = $product->get_meta('_loading_meters', true);
    if (empty($loading_meters) && $length_in_m > 0 && $height_in_m > 0) {
        $loading_meters = round(($length_in_m * $height_in_m) / 2.4, 2); // Round to 2 decimals (adjust as needed)
    }
    
    // Get saved loading weight, or calculate if empty
    $loading_weight = $product->get_meta('_loading_weight', true);
    if (empty($loading_weight) && !empty($loading_meters)) {
        $loading_weight = round($loading_meters * 1750, 2);
    }
    
    // Render Loading Meters field
    woocommerce_wp_text_input(
        array(
            'id' => '_loading_meters',
            'label' => __('Loading meters', 'woocommerce'),
            'desc_tip' => 'true',
            'description' => __( 'Vul hier de laadmeters in', 'woocommerce' ),
            'type' => 'number',
            'custom_attributes' => array(
                'step' => 'any',
                'min' => '0'
            ),
            'value' => $loading_meters // Set calculated default (or saved value)
        )
    );
    
    // Render Loading Weight field
    woocommerce_wp_text_input(
        array(
            'id' => '_loading_weight',
            'label' => __('Loading weight', 'woocommerce'),
            'desc_tip' => 'true',
            'description' => __( 'Vul hier het laadgewicht in', 'woocommerce' ),
            'type' => 'number',
            'custom_attributes' => array(
                'step' => 'any',
                'min' => '0'
            ),
            'value' => $loading_weight // Set calculated default (or saved value)
        )
    );
});

2. Improved Save Logic (Modern Hook)

Replace your existing save code with this more up-to-date version (uses WooCommerce's official product object hook):

add_action('woocommerce_admin_process_product_object', function($product) {
    // Sanitize and save loading meters
    $loading_meters = isset($_POST['_loading_meters']) ? sanitize_text_field($_POST['_loading_meters']) : '';
    $product->update_meta_data('_loading_meters', $loading_meters);
    
    // Sanitize and save loading weight
    $loading_weight = isset($_POST['_loading_weight']) ? sanitize_text_field($_POST['_loading_weight']) : '';
    $product->update_meta_data('_loading_weight', $loading_weight);
});

How It Works

  • Initial Load: For new products (or products without saved values), the fields will auto-fill with your calculated values as soon as you open the product edit page.
  • Manual Edits: If an admin changes the values and saves, those edited values will be stored in the database. The next time you open the product, it will display the saved manual values instead of recalculating.
  • Unit Compatibility: The code automatically handles different WooCommerce dimension units (cm, mm, inches, yards, meters) so your calculations stay accurate regardless of store settings.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:57:50