remove woocommerce checkout fields code example

Example: woocommerce unset custom checkout field

// Conditional function: If one of the special products is in cart return true, else false
function is_in_cart() {
    // Add your special product IDs here
    $ids = array( 45, 70, 75 );

    foreach( WC()->cart->get_cart() as $cart_item ){
        $product_id = version_compare( WC_VERSION, '3.0', '<' ) ? $cart_item['data']->id : $cart_item['data']->get_id();
        if( in_array( $cart_item['data']->get_id(), $ids ) )
            return true;
    }
    return false;
}

add_filter( 'woocommerce_checkout_fields' , 'remove_checkout_fields', 10, 1 );
function remove_checkout_fields( $fields ) {
    if( ! is_in_cart() )
        unset($fields['billing']['billing_company']);

    return $fields;
}

add_action( 'woocommerce_after_order_notes', 'company_details_section', 10, 1 );
function company_details_section( $checkout ){
    // Here your conditional function
    if( is_in_cart() ){

        echo '<div id="my_custom_checkout_field"><h3>' . __('Company Details') . '</h3>';

        woocommerce_form_field( 'delegate_1_name', array(
            'type' => 'text',
            'class' => array( 'my-field-class form-row-wide delegateExists' ),
            'label' => __('Full name') ,
        ) , $checkout->get_value( 'delegate_1_name' ) );

        echo '</div>';
    }
}

Tags:

Misc Example