Reputation: 562
I want to show a payment gateway on the Woocommerce Bookings payment page based on the product's tag and located on the URL extension like:
/checkout/order-pay/5759158/?pay_for_order=true&key=wc_order_75uA3d1z1fmCT
E.g. if the tag's id is "378", then show only "PayPal" gateway and remove other gateways.
I am using Restrict payment gateways based on taxonomy terms in WooCommerce checkout answer code, that allows to restricts the payment gateway based on a product tag, but only on the Woocommerce checkout page.
I need to restrict it on the Woocommerce Bookings payment page as well.
How to restrict the payment gateway based on a product tag in Woocommerce Bookings payment page?
Upvotes: 0
Views: 1297
Reputation: 254398
For order pay pages, you need to loop through order items instead of cart items, to check for product tag terms… To target order pay page use:
if ( is_wc_endpoint_url( 'order-pay' ) ) {
The following code will disable all payment methods except "paypal" when there is an item that belongs to specific product tag term(s) in order pay page (and checkout too):
add_filter( 'woocommerce_available_payment_gateways', 'filter_available_payment_gateways' );
function filter_available_payment_gateways( $available_gateways ) {
// Here below your settings
$taxonomy = 'product_tag'; // Targeting WooCommerce product tag terms (or "product_cat" for category terms)
$terms = array('378'); // Here define the terms (can be term names, slugs or ids)
$payment_ids = array('paypal'); // Here define the allowed payment methods ids to keep
$found = false; // Initializing
// 1. For Checkout page
if ( is_checkout() && ! is_wc_endpoint_url() ) {
// Loop through cart items
foreach ( WC()->cart->get_cart() as $item ) {
if ( ! has_term( $terms, $taxonomy, $item['product_id'] ) ) {
$found = true;
break;
}
}
}
// 2. For Order pay
elseif ( is_wc_endpoint_url( 'order-pay' ) ) {
global $wp;
// Get WC_Order Object from the order id
$order = wc_get_order( absint($wp->query_vars['order-pay']) );
// Loop through order items
foreach ( $order->get_items() as $item ) {
if ( ! has_term( $terms, $taxonomy, $item->get_product_id() ) ) {
$found = true;
break;
}
}
}
if ( $found ) {
foreach ( $available_gateways as $payment_id => $available_gateway ) {
if ( ! in_array($payment_id, $payment_ids) ) {
unset($available_gateways[$payment_id]);
}
}
}
return $available_gateways;
}
Code goes in functions.php file of the active child theme (or active theme). It should work.
See: Conditional Tags in WooCommerce
Related: Restrict payment gateways based on taxonomy terms in WooCommerce checkout
Upvotes: 2