Title: foreeach loop meta_query
Last modified: August 21, 2019

---

# foreeach loop meta_query

 *  [theone581](https://wordpress.org/support/users/theone581/)
 * (@theone581)
 * [6 years, 9 months ago](https://wordpress.org/support/topic/foreeach-loop-meta_query/)
 * Hi,
 * I am looking for assistance on how to load and query (as filters) some custom
   fields using an array and foreeach loop for a front end search bar. Due to the
   need for 11 queries for this project (I’ve shortened the code fields) coding 
   11 if statements will crash my ajax_url and thus limit me to only 9 queries with
   very slow load times.
 * JS CODE BELLOW ******************************************************
 *     ```
       $ = jQuery;
   
       var reportSearch = $("#Report");
       var searchFORM = reportSearch.find("#reportSearch");
   
       searchFORM.submit(function (e){
       	//stops refresh
       	e.preventDefault();
       	//collects input from front end
   
       	var data = {
       		action : "report_search",
       		address : reportSearch.find("#address").val(),
       		unit : reportSearch.find("#unit").val(),
       	}
       	//console.log(data);
   
       	$.ajax({
       		url : ajax_url,
       		data : data,
       		success : function (response) {
       			console.log(response);
       			//resets results viewing on new search
       			reportSearch.find("#sList").empty();
       			for (var i = 0 ; i < response.length ; i++) {
       				//console.log(response[i]);
   
       				//lists the results
       				var html = '<tr id="' + response[i].title + '"><td><a href="' + response[i].permalink + '" target="_blank">' + response[i].title + '</a></td><td>' + response[i].address +'</td><td>' + response[i].unit + '</td></tr>';
       				reportSearch.find("#sList").append(html);
   
       			}
   
       		}
       	});
       });
       ```
   
 * BELLOW IS MY PHP ATTEMPT **************************************************
 *     ```
       add_action( 'wp_ajax_report_search' , 'report_search_callback' );
       add_action( 'wp_ajax_nopriv_report_search' , 'report_search_callback' );
   
       //REPORT AJAX CALLBACK
       function report_search_callback(){
       	if(is_user_logged_in()){
       	header('content-type: application/json');
   
       	//creates empty result var
       	$result = array();
   
       	//loads post type
       	$args = array(
       		"post_type" => "Report",
       		"post_per_page" => -1
       	);
   
       //Creates variable to place front end input
       	$address = "";
       	$unit = "";
   
       	$queryTest = [
       	"address",
       	"unit",
       	];
   
       	foreach ($queryTest as $key => $value) {
       		if (isset($_GET[$value])) {	
       			$args['meta_query'][] = array(
       			'key' => $key, //MUST BE CUSTOM FIELD NAME
       			'value' => $value,
       			'compare' => 'LIKE'
       			);	
       		}
       	}
   
       //init query
       	$report_query = new WP_Query( $args );
   
       	//loops to gather all posts
       	while ( $report_query->have_posts() ) {
   
       		$report_query->the_post();
   
       		//creates json file
       		$result[] = array(
       			"id" => get_the_ID(),
       			"title" => get_the_title(),
       			"address" => get_field('address'),
       			"unit" => get_field('unit'),
       			"permalink" => get_permalink()
       		);
       	}
       	echo json_encode($result);
       	wp_die();
       	} else {
       		echo "Please log in to continue";
       	}
       }
       ```
   
 * The PHP attempt code currently returns no records as I’m assuming it’s not searching
   for the correct key and value in the meta_query.
 * I am trying to avoid using 11 if statements as the ajax_url crashes and will 
   only let me run up to 9 queries at a very slow loading time.
 * BELLOW IS A WORKING IF STATEMENT FOR THE CODE / THIS IS WHAT I HAVE 11 OF ATM*********
 *     ```
       	if (isset($_GET['address'])) {
       		$address = sanitize_text_field( $_GET['address'] );
       		//JSON FILTER
       		$args['meta_query'][] = array(
       			'key' => 'address', //MUST BE CUSTOM FIELD NAME
       			'value' => $address,
       			'compare' => 'LIKE'
       		);	
       	}
       ```
   
 * A rework of the foreEach meta_query might be needed and any help with this would
   be greatly appreciated!
    -  This topic was modified 6 years, 9 months ago by [theone581](https://wordpress.org/support/users/theone581/).
    -  This topic was modified 6 years, 9 months ago by [theone581](https://wordpress.org/support/users/theone581/).

Viewing 1 replies (of 1 total)

 *  Moderator [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * (@bcworkz)
 * [6 years, 9 months ago](https://wordpress.org/support/topic/foreeach-loop-meta_query/#post-11854472)
 * At the very least, use `method: 'POST',` in your .ajax() arguments to get the
   parameters out of the URL. Then in PHP get the passed data with `$_POST`. You
   can then send all the data you like via Ajax.
 * That will not help improve query times when you have 11 different meta query 
   parameters. You might want to pre-process the data and eliminate query arguments
   that would not influence the query. Meta queries are horribly inefficient. If
   you’ve optimized the data beforehand and still get long query times, you may 
   need to consider keeping the related data in a custom table where each possible
   field has its own column. Of course you cannot use WP_Query any longer. You’d
   make your own SQL queries and execute through global $wpdb methods.

Viewing 1 replies (of 1 total)

The topic ‘foreeach loop meta_query’ is closed to new replies.

## Tags

 * [ajax](https://wordpress.org/support/topic-tag/ajax/)
 * [array](https://wordpress.org/support/topic-tag/array/)
 * [foreach](https://wordpress.org/support/topic-tag/foreach/)
 * [json](https://wordpress.org/support/topic-tag/json/)
 * [php](https://wordpress.org/support/topic-tag/php/)

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 1 reply
 * 2 participants
 * Last reply from: [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * Last activity: [6 years, 9 months ago](https://wordpress.org/support/topic/foreeach-loop-meta_query/#post-11854472)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
