Josip Codes
Josip Codes

Reputation: 9521

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?

Upvotes: 4

Views: 12029

Answers (2)

Purnendu Sarkar
Purnendu Sarkar

Reputation: 342

You Can also use woocommerce custom price filter html page or woocommerce archive page or sidebar as you like.(jquery and php)

<script>
<?php
global $wp;
$current_url = home_url( add_query_arg( array(), $wp->request ) );
?>      
        $('select').change(function() {
            //alert("document ready occurred!");
            var min = $( "#min_price" ).val();
            var max = $( "#max_price" ).val();
            //alert(min);
            if(min!=''&& max!=''){
                 var url = "<?php echo $current_url;?>/?min_price="+min+"&max_price="+max;
                window.location.href = url;
            }
        });
    </script>

Upvotes: 0

root
root

Reputation: 470

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).

Upvotes: 7

Related Questions