enable a custom price range query on WC_Product_Query
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
add_filter( 'woocommerce_product_data_store_cpt_get_products_query', 'handle_price_range_query_var', 10, 2 ); | |
function handle_price_range_query_var( $query, $query_vars ) { | |
if ( ! empty( $query_vars['price_range'] ) ) { | |
$price_range = explode( '|', esc_attr($query_vars['price_range']) ); | |
if ( is_array($price_range) && count($price_range) == 2 ) { | |
$query['meta_query']['relation'] = 'AND'; | |
$query['meta_query'][] = array( | |
'key' => '_price', | |
'value' => reset($price_range), // From price value | |
'compare' => '>=', | |
'type' => 'NUMERIC' | |
); | |
$query['meta_query'][] = array( | |
'key' => '_price', | |
'value' => end($price_range), // To price value | |
'compare' => '<=', | |
'type' => 'NUMERIC' | |
); | |
$query['orderby'] = 'meta_value_num'; // sort by price | |
$query['order'] = 'ASC'; // In ascending order | |
} | |
} | |
return $query; | |
} | |
// EXAMPLE USAGE | |
$products = wc_get_products( [ | |
'limit' => 20, | |
'status' => 'publish', | |
'price_range' => '10.25|50', // The first price is separated from the 2nd one with a pipe | |
] ); | |
echo '<ul>'; | |
foreach( $products as $product ) { | |
echo '<li><a href="'.$product->get_permalink().'">'.$product->get_name().' '.$product->get_price_html().'</a></li>'; | |
} | |
echo '</ul>'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment