public
Created

Limit results to post meta via URL

  • Download Gist
gistfile1.aw
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?php
 
add_action( 'pre_get_posts', 'oomskaap_price_range_limiter' );
 
function oomskaap_price_range_limiter( $query ) {
// Only do something if both the start and end values are set in the URL
if ( empty( $_GET['pricestart'] ) || empty( $_GET['priceend'] ) )
return;
 
// Only modify the main query
// 3.3 adds "is_main_query"
if ( method_exists( $query, 'is_main_query' ) ) {
if ( ! $query->is_main_query() ) {
return;
}
}
// Pre-3.3
else {
global $wp_the_query;
if ( $query !== $wp_the_query ) {
return;
}
}
 
// Validate/sanitize
$start = absint( $_GET['pricestart'] );
$end = absint( $_GET['priceend'] );
 
// Add in some more query arguments
$query->query_vars['meta_query'][] = array(
'key' => 'price',
'value' => array( $start, $end ),
'compare' => 'BETWEEN',
'type' => 'NUMERIC',
);
}
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.