根据 WooCommerce 中的特定产品显示或隐藏结账邮政编码字段

问题描述 投票:0回答:1

在 WooCommerce 中,每当选择特定产品时,我都会尝试在结账时隐藏邮政编码字段。我尝试过很多不同的事情。 这是我最后一次尝试:

/**
     * Conditionally remove a checkout field based on products in the cart
     */
    function wc_ninja_product_is_in_the_cart() {
        // Add your special product IDs here
        $ids = array( '9531', '9072', '9035' );;

        // Products currently in the cart
        $cart_ids = array();

        // Find each product in the cart and add it to the $cart_ids array
        foreach( WC()->cart->get_cart() as $cart_item_key => $values ) {
            $cart_product = $values['data'];
            $cart_ids[]   = $cart_product->id;
        }
        // If one of the special products are in the cart, return true.
        if ( ! empty( array_intersect( $ids, $cart_ids ) ) ) {
            return true;
        } else {
            return false;
        }
    }
    function wc_ninja_remove_checkout_field( $fields ) {
        if ( ! wc_ninja_product_is_in_the_cart() ) {
            unset( $fields['billing']['billing_postcode'] );
        }

        return $fields;
    }
    add_filter( 'woocommerce_checkout_fields' , 'wc_ninja_remove_checkout_field' );

<!-- end snippet -->


php woocommerce checkout conditional-operator
1个回答
2
投票
/*Hide postal code field on checkout when specific product is selected.*/
function hide_postal_code_field_based_on_product( $fields ) {
    $target_product_id = 385; // Your product ID
    $product_found = false;
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        if ( $cart_item['product_id'] == $target_product_id ) {
            $product_found = true;
            break;
        }
    }
    if ( $product_found ) {
        $fields['billing']['billing_postcode']['class'][] = 'hide-postal-code';
    }
    
    return $fields;
}
add_filter( 'woocommerce_checkout_fields', 'hide_postal_code_field_based_on_product' );
function hide_postal_code_field_css() {
    ?>
    <style>
        .hide-postal-code {
            display: none !important;
        }
    </style>
    <?php
}
add_action( 'woocommerce_checkout_after_customer_details', 'hide_postal_code_field_css' );
© www.soinside.com 2019 - 2024. All rights reserved.