Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce custom price range in URL

I'm working on project that uses WooCommerce, and needed to add a custom links that would lead to shop page with certain price limitations - I coudn't use the built in WooCommerce price filter widget, but added a static link with following URL:

http://my.domain.com/shop?min_price=0&max_price=2000

Where shop is the page of WooCommerce Shop page, and I just added rest of the parameters in the URL.

When Shop page opens, products are still there, but nothing is filtered - what am I doing wrong? Is this the same principle that Price Filter Widget is using?

like image 966
jOpacic Avatar asked Oct 27 '25 15:10

jOpacic


1 Answers

The reason that your url parameters are not doing anything is that WooCommerce only runs the price filter if the price filter widget is active.

To get around this, take the woocommerce function that initializes the price filter, change the name, and modify it to run the filter even if the widget is not active. Then unhook the woocommerce price filter initialization function and hook yours up.

That is, put this into your functions.php file:

function my_price_filter_init() {
    global $woocommerce;

    if ( ! is_admin() ) {

        unset( $_SESSION['min_price'] );
        unset( $_SESSION['max_price'] );

        if ( isset( $_GET['min_price'] ) )
            $_SESSION['min_price'] = $_GET['min_price'];

        if ( isset( $_GET['max_price'] ) )
            $_SESSION['max_price'] = $_GET['max_price'];

        add_filter( 'loop_shop_post_in', 'woocommerce_price_filter' );
    }
}
remove_action('init', 'woocommerce_price_filter_init');
add_action( 'init', 'my_price_filter_init' );

That is a modification of woocommerce_price_filter_init from widget-price_filter.php . The above function does not load the javascript that runs the price filter widget, so if you need the widget to work also you'll have to put that back in (or just let me know and I'll edit it back in).

like image 120
root Avatar answered Oct 29 '25 07:10

root



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!