根据 WooCommerce 订单支付中的特定产品标签限制支付网关

Restrict payment gateways based on specific product tag in WooCommerce order pay

我想根据产品标签在 Woocommerce 预订支付页面上显示一个支付网关,该支付网关位于 URL 扩展名上,例如:
/checkout/order-pay/5759158/?pay_for_order=true&key=wc_order_75uA3d1z1fmCT

例如如果标签的 id 是“378”,则只显示“PayPal”网关并删除其他网关。

我正在使用 答案代码,它允许根据产品标签限制支付网关,但仅限于 Woocommerce 结帐页面。

我也需要在 Woocommerce 预订支付页面上对其进行限制。

如何在 Woocommerce Bookings 支付页面中根据产品标签限制支付网关?

对于订单支付页面,您需要遍历订单项目而不是购物车项目,以检查产品标签条款……要定位订单支付页面,请使用:

if ( is_wc_endpoint_url( 'order-pay' ) ) {

当订单支付页面中有属于特定产品标签条款的商品时,以下代码将禁用除“paypal”之外的所有支付方式(以及结帐):

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;
}

代码进入活动子主题(或活动主题)的 functions.php 文件。它应该有效。

参见:Conditional Tags in WooCommerce

相关: