I am trying to allow the customer to add a payment method just like he or she can edit their address and everything else.
So, I added this code to the My account => Payment Methods
. But when clicked, it just says that "New payment methods can only be added on checkout" or something like that.
So, any solution to this?
add_action( 'woocommerce_after_account_payment_methods', 'add_payment_method_from_my_account' );
function add_payment_method_from_my_account() { ?>
<a class="button" href="<?php echo esc_url( wc_get_endpoint_url( 'add-payment-method' ) ); ?>">
<?php esc_html_e( 'Add payment method', 'woocommerce' ); ?></a>
<?php
}
You need something completely different, as the desired payment gateways, need to support "add_payment_method" feature (or "tokenization" feature).
So we don't need your code (and all other related code that you have added).
But, we can enable "add_payment_method" feature for some defined payment gateways.
Remove/disable all your related code and use instead the following hooked function:
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 (slugs)
$allowed_payment_method_ids = array('bacs', 'cheque', 'cod');
if ( in_array($payment_gateway->id, $allowed_payment_method_ids ) && $feature === 'add_payment_method' ) {
$supports = true;
}
return $supports;
}
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
This time "Payment methods" menu item appears in My account menu items and when going to "Payment methods" section, there is a functional "Add payment method" button.