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

  • What do you want to escape? On what basis? As I understand it, the value for your tax query is already given as query var, which you now want to use for the tax query. Are you talking about validation? I don't see any escaping needs here... – tfrommen Jan 23 '14 at 16:11
  • @tf, I'd like to escape custom query variables, but not sure what's the right way to do it. As far as I understand get_query_var doesn't escape the value that it gets from $wp_query that in turn came from a URL. And because it's originally from URL, it needs escaping. I'm a bit confused to be honest. – dashaluna Jan 23 '14 at 16:37
  • 1
    get_query_var doesn't escape data, but WP_Query does before performing the database query. However, if you want, you can use the php filter_var function with a proper filter constant, like: filter_var( get_query_var( 'industry' ), FILTER_SANITIZE_STRING ); – gmazzap Jan 23 '14 at 18:52
  • 1
    While I agree with @G.M., I don't think you have to worry about escaping anything in this scenario. – MikeNGarrett Jan 24 '14 at 4:38
  • Thanks, @G.M. and @MikeNGarrett. I was thinking that WP_Query should handle this as I'm using it instead of my custom SQL. Just got a bit confused. I think I'm not gonna worry and leave it up to WP_Query to handle it. Thanks for advice! – dashaluna Jan 26 '14 at 20:54

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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