WooCommerce 存款:仅保留特定的存款运输方式

WooCommerce deposits: Keep only specific shipping methods for deposits

我使用 WooCommerce Deposits 插件,如果客户选择用定金付款,我想隐藏除“本地取货”以外的所有其他送货方式。

客户可以在产品页面选择是否支付定金(例如 10%)或支付订单的全额。送货方式flat_rate用于发送订单(如果他们是全额支付)并且应该被隐藏,因为客户需要先支付剩余的订单金额并在(线下)商店当地取货。

产品页面上的选择:

<input type="radio" name="wc_deposit_option" value="yes" id="wc-option-pay-deposit">
<input type="radio" name="wc_deposit_option" value="no" id="wc-option-pay-full" checked="checked">

我试图将可用的隐藏运输方法代码片段与 _wc_deposit_enabled 元数据结合起来,但我无法弄清楚。帮助将不胜感激。

/**
     * Are deposits enabled for a specific product
     * @param  int $product_id
     * @return bool
     */
    public static function deposits_enabled( $product_id, $check_variations = true ) {
        $product = wc_get_product( $product_id );

        if ( ! $product || $product->is_type( array( 'grouped', 'external' ) ) ) {
            return false;
        }

        $setting = get_post_meta( $product_id, '_wc_deposit_enabled', true );

        if ( $check_variations && empty( $setting ) ) {
            $children = get_children( array(
                'post_parent' => $product_id,
                'post_type' => 'product_variation',
            ) );

            foreach ( $children as $child ) {
                $child_enabled = get_post_meta( $child->ID, '_wc_deposit_enabled', true );
                if ( $child_enabled ) {
                    $setting = $child_enabled;
                    break;
                }
            }
        }
        
        if ( empty( $setting ) ) {
            $setting = get_option( 'wc_deposits_default_enabled', 'no' );
        }

        if ( 'optional' === $setting || 'forced' === $setting ) {
            if ( 'plan' === self::get_deposit_type( $product_id ) && ! self::has_plans( $product_id ) ) {
                return false;
            }
            return true;
        }
        return false;
    }

以下代码将只保留存款的本地取货运输方式(对于 WooCommerce 存款)

add_filter( 'woocommerce_package_rates', 'only_local_pickup_for_deposits', 100, 2 );
function only_local_pickup_for_deposits( $rates, $package ) {
    $has_deposit = false;

    // Loop through cart items for the current shipping package
    foreach( $package['contents'] as $item ) {
        if ( isset($item['is_deposit']) && $item['is_deposit'] ) {
            $has_deposit = true;
            break; // Stop the loop
        }
    }

    // If deposit is enabled for a cart item
    if( $has_deposit ) {
        // Loop through shipping rates
        foreach ( $rates as $rate_key => $rate ) {
            // Remove all shipping methods except "Local pickup" 
            if ( 'local_pickup' !== $rate->method_id ) {
                unset($rates[$rate_key]);
            }
        }
    }
    return $rates;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该有效。