Removing price suffix based on user role

五迷三道 提交于 2021-02-10 07:11:51

问题


Having failed at adding a suffix based on User Role because it wont display the Woo price display shortcode, I'm now approach the problem from the other direction - I have added the suffix to Woos tax tab, and now instead want to remove the suffix (from all user roles except one).

I found this code on github to remove the suffix from products:

add_filter( 'woocommerce_get_price_suffix', 'custom_woocommerce_get_price_suffix', 10, 2 );

function custom_woocommerce_get_price_suffix( $price_display_suffix, $product ) {
  if ( ! $product->is_taxable() ) {
    return '';
  }
  return $price_display_suffix;
}

and I have modified it to hide the suffix from certain user types

add_filter( 'woocommerce_get_price_suffix', 'custom_woocommerce_get_price_suffix', 10, 2 );

function custom_woocommerce_get_price_suffix( $price_display_suffix, $product ) {

 // check current user role
    $user = wp_get_current_user();
    $roles = ( array ) $user->roles;

   if ( in_array( 'administrator', $roles ) ) {
        $price = $your_suffix;
    } elseif ( in_array( 'default_wholesaler', $roles ) ) {
        $price = '$your_suffix';

    return '';
  }
  return $price_display_suffix;
}

This worked, however I had to switch the users (I want Admin and Wholesalers to see the suffix) and put in Customers, etc.

The problem is that guest customers still see the suffix.

Could someone suggest a way of hiding the suffix from anyone except the logged in 'default-wholesaler' user and 'Administrator'?

Thanks!


回答1:


You could use the following for this.

This works for the administrator role! you can add the other role yourself as an 'exercise'

function custom_woocommerce_get_price_suffix( $html, $product, $price, $qty ) { 
    // check current user role
    $user = wp_get_current_user();
    $roles = ( array ) $user->roles;

    // if NOT in array user roles
    if ( !in_array( 'administrator', $roles ) ) {
        $html = '';
    }

    return $html;
}
add_filter( 'woocommerce_get_price_suffix', 'custom_woocommerce_get_price_suffix', 10, 4 );


来源:https://stackoverflow.com/questions/60528647/removing-price-suffix-based-on-user-role

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!