So first of all you’ll want to make sure that you want to and your WHERE
clause in. posts_where
will fire for (almost) every query so you want to be sure that you’re adding it to the right one. This can be done with the use of conditional tags.
Note: The WHERE 1=1
is added because it means a valid WHERE
expression is added, and can be extended using the posts_where
filter (i.e by just adding AND X=Y
). Infact WordPress hardcodes the WHERE
and adds in the conditionals – so it needs something to be there to be sure that the SQL query is valid
add_filter('posts_where', 'wpse55985_posts_where',10,2);
function wpse55985_posts_where($where, $query){
global $wpdb;
//$query is a WP_Query object
if( $query->is_main_query() && is_tax('my-tax') ){
//This is the main query for the 'my-tax' taxonomy page
if( isset($_GET[POSTS_END_DATE_NAME]) && isset($_GET[POSTS_START_DATE_NAME]) ){
//Variables are set.
$start = $_GET[POSTS_START_DATE_NAME];
$end = $_GET[POSTS_END_DATE_NAME];
//Append our additional 'WHERE' clause
$where .= $wpdb->prepare(
" AND {$wpdb->posts}.post_date BETWEEN %s AND %s ", $start,$end
) ;
}
}
return $where
}
Explanation
-
First of all use
is_main_query()
to check that this is the query that is the ‘main’ query for the page. The conditionals all relate to this main query. So I’m checking that this is the main query, and the query is for the taxonomy ‘my-tax’ – in particular that the ‘my-tax’ taxonomy page is being viewed. So the above should only filter posts on themy-tax
taxonomy page. Seeis_tax()
. Otherwise, we just return the$where
clause without doing anything. -
Check that the
$_GET
variables you are after are set. You should really be registering custom query variables and using the$query->get()
method than dealing with$_GET
directly. If they aren’t set, we don’t alter the query. -
Use the
$wpdb
class to get the post table name and to safely prepare the query. See this Codex page, and the last part of this article. This part is vital to protect yourself form SQL injection.
Please note, I’ve not tested this, and there could be syntax errors.