php - Woocommerce Payment Gateway Based Checkout Fields

881

I am looking to remove checkout fields based on the payment gateway selected.

I have added following code in function.php, but it is not working. The problem I am facing is, it is going in If condition, but unset is not working inside if condition. When I tried to echo inside if condition, it is showing up in the browser.

add_filter( 'woocommerce_checkout_fields' , 'custom_override_checkout_fields' );
function custom_override_checkout_fields( $fields ) {

    if($_POST['payment_method'] === "wcwcPDpg"){

       echo "this";
       unset($fields['billing']['billing_first_name']);
       unset($fields['billing']['billing_last_name']);
       unset($fields['billing']['billing_company']);
       unset($fields['billing']['billing_address_1']);
       unset($fields['billing']['billing_address_2']);
       unset($fields['billing']['billing_city']);
       unset($fields['billing']['billing_postcode']);
       unset($fields['billing']['billing_country']);
       unset($fields['billing']['billing_state']);
       unset($fields['billing']['billing_phone']);
       unset($fields['order']['order_comments']);
       unset($fields['billing']['billing_email']);
       unset($fields['account']['account_username']);
       unset($fields['account']['account_password']);
       unset($fields['account']['account_password-2']);
    }


   return $fields;
}

When I remove the if condition, the fields are unset, however, I just want to unset for specific payment gateway only.

any help appreciated :)

59

Answer

Solution:

Try

if (WC()->session->chosen_payment_method == "wcwcPDpg") {

instead of

if($_POST['payment_method'] === "wcwcPDpg"){

Then add this to your child theme's functions.php so your filter is applied each time the payment gateway is toggled:

function filter_woocommerce_update_order_review_fragments( $array ) { 
   ob_start();
   wc_get_template( 'checkout/form-billing.php', array( 'checkout' => WC()->checkout() ) );

   $array[".woocommerce-billing-fields"] = ob_get_clean();
   return $array; 
}; 

add_filter( 'woocommerce_update_order_review_fragments', 'filter_woocommerce_update_order_review_fragments', 10, 1 )

I suspect there's a better way to do this, but it's my first attempt. Please post an update here if you have a better solution.

People are also looking for solutions to the problem: php - How Do I Pass Which Item I Want To Delete?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.