Last active
November 2, 2023 09:08
-
-
Save allysonsouza/ef6d04e0fe5f5854ab45198595f47b3a to your computer and use it in GitHub Desktop.
[Custom filter by price with pre_get_posts] #woocommerce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function woocommerce_pre_get_posts( $query ) { | |
if ( ! is_admin() && is_post_type_archive( 'product' ) && $query->is_main_query() ) { | |
// Option 1 | |
$args = array( | |
array( | |
'meta_key' => '_price', | |
'value' => array( 50, 500 ), | |
'compare' => 'BETWEEN' | |
) | |
); | |
// Option 2 | |
$args = array( | |
array( | |
'meta_key' => '_price', | |
'value' => array( 50, 500 ), | |
'compare' => 'BETWEEN', | |
'type' => 'NUMERIC' | |
) | |
); | |
// Option 3 | |
$args = array( | |
'relation' => 'AND', | |
array( | |
'meta_key' => '_price', | |
'value' => 50, | |
'compare' => '>=', | |
), | |
array( | |
'meta_key' => '_price', | |
'value' => 500, | |
'compare' => '<=', | |
) | |
); | |
$query->set( 'meta_query', $args ); | |
} | |
} | |
add_action( 'pre_get_posts', 'woocommerce_pre_get_posts', 20 ); | |
Filter (show) woocommerce products where product price is between 50 and 500. You can use any of the 3 options all will give same result.
And what if i wanted to show only products that have an image? How would that work with the pre-get filter? Thanks in advance.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What is this for? I didn't get this concept.