I am building a WordPress plugin that looks for different custom variables in the URL.

The way I am able to achieve that right now is with this code:

function add_custom_query_var( $vars){
  $vars[] = "variable1";
  return $vars;
}
function add_custom_query_var1( $vars1){
  $vars1[] = "variable2";
  return $vars1;
}
add_filter( 'query_vars', 'add_custom_query_var' );
add_filter( 'query_vars1', 'add_custom_query_var1' );

I feel like this code is redundant and was wondering if there is a better way to do this.

Thanks

1
1

I pretty sure this filter lets you add an array of variables. I’ve not tested this:

function add_custom_query_vars( $vars ){
  $vars[] = "variable1";
  $vars[] = "variable2";
  $vars[] = "variable3";
  //... etc
  return $vars;
}

add_filter( 'query_vars', 'add_custom_query_vars' );

Or another way of doing it would be to do this:

function add_custom_query_vars( $vars ){
  array_push($vars, "variable1", "variable2", "variable3");
  return $vars;
}

add_filter( 'query_vars', 'add_custom_query_vars' );

Leave a Reply

Your email address will not be published. Required fields are marked *