seancojr
10/30/2011 - 8:11 AM

Limit results to post meta via URL

Limit results to post meta via URL

<?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',
	);
}

?>