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?

1 Answer 1


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.

  • 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). Nov 1, 2011 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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