dptdb84606 2018-02-02 18:36 采纳率: 0%
浏览 73
已采纳

too long

I attempted to ask Customizr support what my code was running into, but they basically said they do not support 3rd party plugins such as Woocommerce

I needed to restrict the payment types based on what folk were buying on the site. For example, the Check payment type is only available for people buying lessons.

Here is the code that does this:

<?php
add_filter( 'woocommerce_available_payment_gateways', 
'threshold_unset_gateway_by_category' );

function threshold_unset_gateway_by_category( $available_gateways ) {
global $woocommerce;
$unset = false;
$category_ids = array( 22, 21, 25, 20);
foreach ( $woocommerce->cart->get_cart() as $key => $values ) {
    $terms = get_the_terms( $values['product_id'], 'product_cat' );    
    foreach ( $terms as $term ) {        
        if ( in_array( $term->term_id, $category_ids ) ) {
            $unset = true;
            break;
        }
    }
}
    if ( $unset == true ) unset( $available_gateways['cheque'] );
    return $available_gateways;
}

I have dug into the Customizr files but I cannot find any conflict. The Wordpress files can be a bit convoluted, so I might be barking up the wrong tree.

  • 写回答

2条回答 默认 最新

  • doupiao9318 2018-02-12 18:04
    关注

    So the solution to this was much more simpler than I expected. Thank you @LoicTheAztec for the tips, I utilized Loic's code for better optimization. The fix was to check if the user is admin

     if ( is_admin() ) {
            return $available_gateways;
        }
    

    Then put the rest of the code in an else. Here is the full solution:

    add_filter( 'woocommerce_available_payment_gateways', 'categories_unset_cheque_gateway', 99, 1 );
    function categories_unset_cheque_gateway( $gateways ){
        if (is_admin()){
            return $gateways;
        }
        // BELOW define your categories in the array (can be IDs, slugs or names)
        else{
            $categories = array( 15 );
            // Loop through cart items checking for specific product categories
            foreach ( WC()->cart->get_cart() as $cart_item )
                if( has_term( $categories, 'product_cat', $cart_item['product_id'] ) ){
                    unset( $gateways['cheque'] );
                    break; // Stop the loop
                }
            return $gateways;
            }   
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题