Ask your WordPress questions! Pay money and get answers fast! (more info)

Woocommerce Sale Filter WordPress

  • SOLVED

Hey Guys,
I want to create a simple filter which will modify the woocommerce query to display sale products only if a URL parameter is passed.

(eg; http://domain.com/shop/category/jumpsuits/?sale=1)

I'm not 100% sure about how to do this. I have seen a couple of methods of using pre_get_post but can't seem to get it to work.

I've found a snippet (https://gist.github.com/daltonrooney/3723745#file-woocommerce_sale_products-php-L36) which shows the meta_query to be parsed when checking if the products are on sale or not.

Answers (3)

2013-09-05

Liam Bailey answers:

Hi there,

What you want is this:

add_action('pre_get_posts','sale_items');

function sale_items($query) {
if (!is_admin() && ($query->is_post_type_archive( 'product' ) || $query->is_tax( get_object_taxonomies( 'product' ))) && isset($_GET['sale']) && $_GET['sale'] == 1) {
$meta_query = array(
array(
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
);
$query->set('meta_query',$meta_query);
}
}


floy comments:

I think thats on the right track!

Although it throws an error.

Parse error: syntax error, unexpected '{'

on this line:
if (!is_admin() && ($q->is_post_type_archive( 'product' ) || $q->is_tax( get_object_taxonomies( 'product' )) && isset($_GET['sale']) && $_GET['sale'] == 1) {


Liam Bailey comments:

Ok, I have fixed the error - updated the code in my original answer :-)


floy comments:

Now I get a new error on the same line!

Fatal error: Call to a member function is_post_type_archive() on a non-object in


Liam Bailey comments:

Ok, sorry that is my bad. I have revised the code in my original answer.


floy comments:

Works perfectly

2013-09-05

Hariprasad Vijayan answers:

Hi,

Do you want to use a url parameter in your wp query to filter the result based on parameter or just need to display based on parameter?

If you want just show/hide result, you can use the following method

<?php
if(!empty($_GET['parameter']))
{
// result
}

?>
please ask you have doubt.

2013-09-05

Arnav Joy answers:

try this

add_action('pre_get_posts','sale_items');



function sale_items($query) {

if (!is_admin() && ($q->is_post_type_archive( 'product' ) || $q->is_tax( get_object_taxonomies( 'product' ))) && isset($_GET['sale']) && $_GET['sale'] == 1) {

global $pagenow, $typenow, $wp_query;

$query->query_vars['meta_compare'] = '>';
$query->query_vars['meta_value'] = 0;
$query->query_vars['meta_key'] = '_sale_price';

}

}