phpwordpresswoocommerceurlvariables

Enable or disable WooCommerce products sale price based on URL variable


I am trying to display sale prices to users that enter the website with the following link www.example.com?sale and show regular prices to the rest of users. The code below does the job for single products, sale price is shown only to users with this url www.example.com?sale, but on car it switches back to regular price. And only works for single products. I'm pretty new with woocommerce and php, hope someone can give me a hand with this. Thanks so much for your help!

function custom_wc_get_sale_price( $sale_price, $product ) {
    if (isset($_GET['sale'])) {
        return $sale_price;
} else {
        return $product->get_regular_price();
}

}
add_filter( 'woocommerce_product_get_sale_price', 'custom_wc_get_sale_price', 50, 2 );
add_filter( 'woocommerce_product_get_price', 'custom_wc_get_sale_price', 50, 2 );

Solution

  • You need to set this url variable to WC session to avoid loosing it when Url change:

    // Early enable guest customer WC_Session
    add_action( 'init', 'wc_session_enabler' );
    function wc_session_enabler() {
        if ( is_user_logged_in() || is_admin() )
            return;
    
        if ( isset(WC()->session) && ! WC()->session->has_session() ) {
            WC()->session->set_customer_session_cookie( true );
        }
    }
    
    // Get "sale" url variable and set custom WC session variable
    add_action( 'init', 'enable_sale_to_wc_session' );
    function enable_sale_to_wc_session() {
        if ( isset($_GET['sale']) ) {
            WC()->session->set('has_sale', '1');
        }
    }
    
    // Enable sale price if it's set on products when 'sale' is as an URL variable
    add_filter( 'woocommerce_product_get_price', 'enabling_sale_price', 1000, 2 );
    add_filter( 'woocommerce_product_get_sale_price', 'enabling_sale_price', 1000, 2 );
    add_filter( 'woocommerce_product_variation_get_price', 'enabling_sale_price', 1000, 2 );
    add_filter( 'woocommerce_product_variation_get_sale_price', 'enabling_sale_price', 1000, 2 );
    function enabling_sale_price( $price, $product ) {
        if ( isset($_GET['sale']) || WC()->session->get('has_sale') ) {
            return $price;
        } else {
            return $product->get_regular_price();
        }
    }
    
    // Remove custom WC session variable on thankyou page
    add_action( 'woocommerce_thankyou', 'remove_enable_sale_from_wc_session' );
    function remove_enable_sale_from_wc_session() {
        if ( WC()->session->get('has_sale') ) {
            WC()->session->__unset('has_sale');
        }
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.