0

the following code: Set product sale price programmatically in WooCommerce 3 works perfectly.

Also its continuation: Set programmatically product sale price and cart item prices in Woocommerce 3.

However I'd like to exclude an user role from this function altogether, how can I do that?

I added the following to the code above to no avail: if ( ! wc_current_user_has_role( 'trader' ) ) return $product->get_regular_price();

Thanks

1 Answers1

0

After asking around and trying it out, the following code manages to achieve what I need. For future reference if someone else needs it:

// Generating dynamically the product "regular price"
add_filter( 'woocommerce_product_get_regular_price', 'custom_dynamic_regular_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_regular_price', 'custom_dynamic_regular_price', 10, 2 );
function custom_dynamic_regular_price( $regular_price, $product ) {
    if( empty($regular_price) || $regular_price == 0 )
        return $product->get_price();
    else
        return $regular_price;
}


// Generating dynamically the product "sale price"
add_filter( 'woocommerce_product_get_sale_price', 'custom_dynamic_sale_price', 10, 2 );
add_filter( 'woocommerce_product_variation_get_sale_price', 'custom_dynamic_sale_price', 10, 2 );
function custom_dynamic_sale_price( $sale_price, $product ) {
    $user = wp_get_current_user();
    $rate = 0.9;
    
    if( in_array( 'trader', (array) $user->roles ) ) {  
        return $product->get_regular_price() * $rate;
    }
    else
    {
         if( empty($sale_price) || $sale_price == 0 )
            return $product->get_regular_price() * $rate;
         else
            return $sale_price;
    }
};

// Displayed formatted regular price + sale price
add_filter( 'woocommerce_get_price_html', 'custom_dynamic_sale_price_html', 20, 2 );
function custom_dynamic_sale_price_html( $price_html, $product ) {
    if( $product->is_type('variable') ) return $price_html;

    $user = wp_get_current_user();
    if( in_array( 'trader', (array) $user->roles ) ) {  
        $price_html = wc_price($product->get_regular_price() );

    return $price_html;
    }
    else
    {
        $price_html = wc_format_sale_price( wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) ), wc_get_price_to_display(  $product, array( 'price' => $product->get_sale_price() ) ) ) . $product->get_price_suffix();

    return $price_html;
    }
    
}
add_action( 'woocommerce_before_calculate_totals', 'set_cart_item_sale_price', 20, 1 );
function set_cart_item_sale_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // Iterate through each cart item
    foreach( $cart->get_cart() as $cart_item ) {
        $price = $cart_item['data']->get_sale_price(); // get sale price
        $cart_item['data']->set_price( $price ); // Set the sale price

    }
}