How to correctly escape query variables to be used in WP_Query

I’ve got custom query variables that are added via query_vars. For example, ‘industry’.

In pre_get_posts action I construct and add taxonomy query if there is a value for the ‘industry’ parameter, like so:

add_action( 'pre_get_posts', 'alter_posts');
function alter_posts( $q ) {
    $tax_query = array();

    // industry taxonomy
    if ( get_query_var( 'industry' ) ) {
        $tax_query[] = array(
            'taxonomy' => $my_taxonomy,
            'field' => 'slug', 
            'terms' => get_query_var( 'industry' )
        );
    }

    // set all previously determined values to the query
    $q->set( "tax_query", $tax_query );
}

How do I correctly escape query variable that I get via get_query_var( 'industry' )?

Do I use esc_sql function, like so esc_sql( get_query_var( 'industry' ) ) ? What’s the correct way to handle the escaping of query variables?

Many thanks,
Dasha

1
1

The function for the pre_get_posts action uses a WP_Query object (http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts)

When using functions such as get_posts or classes such as WP_Query and WP_User_Query, WordPress takes care of the necessary sanitization in querying the database. However, when retrieving data from a custom table, or otherwise performing a direct SQL query on the database – proper sanitization is then up to you.

— Code Tuts+: Data Sanitization and Validation With WordPress

So in this case, you do not have to escape the query vars.

Leave a Comment