How to Display Custom Payment Fields When Selecting a Payment Method in WooCommerce Checkout?

111 views Asked by At

I have a custom payment gateway in WooCommerce, and I want to display additional payment fields when users select this payment method on the checkout page. Currently, I am using the payment_fields() method, but I'm encountering issues with the form display. Can someone guide me on how to properly show my custom payment fields when the user clicks on my payment method during the checkout process?

    public function payment_fields()
    {
        $cc_form = new WC_Payment_Gateway_CC();
        $cc_form->id = $this->id;
        $cc_form->supports = $this->supports;
        $cc_form->form();
    }

If I load the payment_fields() field in the construct as $this->payment_fields(), the form is displayed at the top of the page, but I do not like this. When my payment method is clicked, I want this form to appear instead of the description text. If I don't add it to the construct, the form doesn't appear anywhere.

1

There are 1 answers

0
LoicTheAztec On

First, try to add/replace in your constructor function:

$this->has_fields = true;

Then try to add/replace (after the constructor function):

public function payment_fields() {
    if ( $this->supports( 'custom_credit_card_form' ) ) {
        $this->credit_card_form();
    }
}

To finish, try to add the following outside plugins_loaded hooked function *(that handles your custom payment gateway class). Inside the function, replace your_payment_id with the correct payment method ID.

add_filter( 'woocommerce_payment_gateway_supports', 'filter_payment_gateway_supports', 10, 3 );
function filter_payment_gateway_supports( $supports, $feature, $payment_gateway ) {
    // Here in the array, set the allowed payment method IDs
    $allowed_payment_method_ids = array('your_payment_id');

    if ( in_array($payment_gateway->id, $allowed_payment_method_ids ) && $feature === 'custom_credit_card_form' ) {
        $supports = true;
    }
    return $supports;
}

It could work.