Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@allysonsouza
Last active November 2, 2023 09:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allysonsouza/ef6d04e0fe5f5854ab45198595f47b3a to your computer and use it in GitHub Desktop.
Save allysonsouza/ef6d04e0fe5f5854ab45198595f47b3a to your computer and use it in GitHub Desktop.
[Custom filter by price with pre_get_posts] #woocommerce
<?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 );
@santanup789
Copy link

What is this for? I didn't get this concept.

@KamranSyed
Copy link

KamranSyed commented Jun 15, 2020

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.

@NickV1995
Copy link

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