Search code examples
woocommercehidesuffix

Removing price suffix based on user role


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!


Solution

  • 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 );