Support » Developing with WordPress » Multiple meta query get high server load.

  • This is my code i have 50+ meta query. is there any option to optimize query.

    global $wpdb;
    	$requestData = $_GET['profile'];
    	   $meta_query = array('relation' => 'AND');
    		foreach ($requestData as  $key => $value) {
    			$meta_query[] = array(
    				'key' => $value,
    				'value' => '1',
    				'compare' => '='
    		$args = array( 'post_type' => 'healthcare', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_query' => $meta_query);
            $loop = new WP_Query( $args );
    		$total = $loop->found_posts;
    		$post_ids = wp_list_pluck( $loop->posts, 'ID' );
    		$ids = implode(',', $post_ids);
    		echo $total.'<input type="hidden" name="matchids" value="'.$ids.'" />';
    • This topic was modified 4 months, 2 weeks ago by  Abhay Yadav.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz


    Do anything possible to limit the meta criteria. It’s hard to imagine a situation where all 50+ criteria are all essential. For example, only add criteria specifically selected by the user, do not use default values.

    Build your own SQL query instead of relying on WP_Query. Only SELECT the ID field you want to avoid getting extraneous data you will not use. Run the query using the global $wpdb object. You cannot use WP_Query methods like WP_Query::found_posts() of course, but equivalent functions are available.

    Nothing will help your query; it will always be slow. You are attempting to grab rows based on the meta_value column, but the meta_value column is not indexed. (The WordPress documentation should warn developers about the server impacts of querying based on meta values.)

    If this is really important to you, give some thought to creating your own custom table where the “meta keys” are columns in the table. Your new query (which will not use WP_Query) will be more than a hundred times faster, and possibly more than a thousand times faster.

    And even though it is probably safe in your example code, using unverified $_GET data in a query is going to get you into a lot of trouble in the future.

    @bcworkz , @diondesigns

    Thanks For suggestion.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.