WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am altering the WordPress query, using the posts_where hook, when a (custom) query variable is set as follows:

add_filter('posts_where', 'my_posts_where' );
function my_posts_where( $where ){
    global $wp_query;

    if( isset( $wp_query->query_vars['customvar'] )) {
        $custom_Var = $wp_query->query_vars['customvar'];
        $where .= " AND wp_MyTable.Column ='".$custom_Var."' ";
    return $where;

This works well, but I want to sanitize it. In particular, I've tried using $wpdb->prepare() method:

$where .= $wpdb->prepare(" AND wp_MyTable.Column = %s", $custom_Var);

But this doesn't work (I just get a blank page). Why is this and is there another / better way of sanitizing the variable?

share|improve this question
up vote 1 down vote accepted

Your last prepare() snippet should work just fine, check that you have $wpdb declared as global in your function.

Also blank page seems extreme, enable WP_DEBUG if not yet and see if there are any specific errors that cause it.

share|improve this answer
Many thanks Rarst. I could have sworn that is what I had done (and declared $wpdb as global). I had done something silly - maybe an AWOL semi-colon. It works now anyhow, (with $wpdb declared global). – Stephen Harris Nov 1 '11 at 19:51

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.