Question

I have 2 functions that use the same $args for the WP_Query class. How can i make it so I have to define the WP_Query class only once, and share all the returns, i.e. I should be able to loop through the query in the two functions without having to define it in each one.

Example:

function first_function(){
  $args = array('post_type' => 'accomodation', 'posts_per_page' => 4, 'meta_query' => array('key' => 'accomodation_type', 'value' => get_query_var('accomodation_type')));
  $query = new WP_Query($args);

  while ($query->have_posts()){
   $query->the_post();

   echo '<h1>' get_the_title() '</h1>';
  }
}
add_action('load_first_function', 'first_function');

function second_function(){
  $args = array('post_type' => 'accomodation', 'posts_per_page' => 4, 'meta_query' => array('key' => 'accomodation_type', 'value' => get_query_var('accomodation_type'));
  $query = new WP_Query($args);

  while ($query->have_posts()){
   $query->the_post();

   echo '<h1>' get_the_title() '</h1>';
  }
}
add_action('load_second_function', 'second_function');
Was it helpful?

Solution

If you want to reduce code duplication, then extract the code into its own function, e.g.:

function get_xyz_query_args( ) : array {
    return array('post_type' => 'accomodation', 'posts_per_page' => 4, 'meta_query' => array('key' => 'accomodation_type', 'value' => get_query_var('accomodation_type')));
}

....

$args = get_xyz_query_args();
$q = new WP_Query( $args );

However, there is very little performance to be gained by recycling the WP_Query object, and potential losses if it's done correctly. The complexity introduced would mean new bugs.

Since WP stores posts it fetches and post meta in WP_Cache, the second WP_Query only needs to fetch post IDs. On top of that, any caching plugin or object cache present can eliminate the database query completely.

So this is not worth doing if performance is your goal, there are better ways.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top