Use query->set or make new query?

I’m writing a loop for multi post types with meta_key filters. The filters are inputs from visitors. When visitor click a link(filter), The form submitted and I get the filter. Now, should I just use $query->set() to change the query args, or should I submit new query?
Currently I’m using this function to get arguments from input and pass the arguments to wp_query:

function get_args($args){
$defaults= array( 
   // some standard query args
   )
$args = wp_parse_args ( $args, $defaults );
extract ( $args );
if(!empty($args['filter'])){
   switch ($args['type']){
      case 'top_voted':
         $args['post_type'] = 'docs';
         $args['meta_key'] = '_vote_total';
         $args['order'] = 'DESC';
         $args['orderby']='meta_value_num';
       break;
      case 'unanswered_questions':
         $args['post_type] = 'topics';
         $args['blabla'] = 'blabla;
      break;
      default:
          blabla;
       break;
}
return $args;
}

In the template, I use this:

Read More
$key = isset( $_POST['filter'] ) ? array_keys($_POST['filter']) : null;
$query_args = get_args(array('user_id'=>$user_id, 'filter'=$key));
$r = new WP_Query( $query_args);

In the above example, I think I’m using new query each time the filter changes. If query->set() or other filters can improve the performance, please help me understand how to do it. Thanks!

Related posts

Leave a Reply

1 comment

  1. If you can alter a query before it runs, then do so and save the database some work. You might be able to alter the query with query->set() and if not you can use the posts_where, posts_fields, etc filters. It is hard to say whether any of that is best for you without more information.

    Edit:

    Another question, what kind of ‘page’ is this loading on? Here is my guess: you created a ‘Page’ from wp_admin->Pages, and probably assigned a custom built page template. If that is the case you probably can’t mess with the main query as its job is going to be to load the ‘Page’ you created, which means you seem to be on the right track with creating the new query.