WooCommerce - 添加过滤器以显示(或隐藏)自定义结帐字段,如果产品ID == #


Woocommerce - Add filter to display (or hide) custom checkout field if product ID == #

我创建了一个"my_custom_field"文本区域,作为默认billing_first_name,billing_address等。现在我想隐藏这个字段,如果产品 ID # 在购物车中。因此,我需要检查产品ID == #,因此从结帐中删除my_custom_field。

否则(也许更好?),我可以检查产品ID == #,并为该特定ID(或类别)创建自定义字段。你有什么建议?

您可以尝试此操作,以适应您的自定义字段和产品 ID

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields ( $fields ){
    if ( count( WC()->cart->get_cart() ) == 0 ) {
        return $fields;
    }
    foreach ( WC()->cart->get_cart() as $key => $item ) {
        if( in_array( $items[ 'product_id' ], array('1','2','3') ) ){
            unset( $fields[ 'my_custom_field' ] );
            break;
        }
    }
    return $fields;
}