phpwordpresswoocommercediscount

Woocommerce global percentage discount on simple products if customer is logged in


I'm looking for advice on what's wrong with the following function.

My goal in this example is to apply a 50% off discount to all WooCommerce simple products, as long as the user is logged in.

function tier_pricing_logic() {  

    if ( is_user_logged_in() ) {  

        function assign_tier_pricing( $price, $product ) {
            $price = $price * 0.5; // Set all prices for simple products to 50% off.    
        }   
        return $price; 

        add_filter('woocommerce_product_get_price', 'assign_tier_pricing', 90, 2 );
        add_filter('woocommerce_product_get_regular_price', 'assign_tier_pricing', 90, 2 );     
    }

}                  
add_action( 'init', 'tier_pricing_logic' );

This function has no effect on the prices, am I approaching this all wrong?


Solution

  • Here you don't need the init hook and your IF statement needs to be inside the hooked function, so try that instead (for simple products):

    add_filter('woocommerce_product_get_price', 'assign_tier_pricing', 90, 2 );
    add_filter('woocommerce_product_get_regular_price', 'assign_tier_pricing', 90, 2 );
    function assign_tier_pricing( $price, $product ) {
        if ( is_user_logged_in() && $product->is_type('simple') ) { 
            $price *= 0.5; // Set all prices for simple products to 50% off.    
        }   
        return $price;   
    }