wp-excpert

Finding post basded on post meta value in WP_Query

Rencently I was working on a Custom Post Type plugin under the banner of RND Experts, where the user will enter name of the city and the field will get saved in the wp_post_meta table. The client has request to create a shortcode where we can filter Post on the basis of Single city or Multiple comma seprated cities.

Here is the code I’ve written to accomplish the requirement.

$atts = shortcode_atts( array(
		'city' => '',
	), $atts 
);

$args = array(
		'post_type' 		=> 'wp_property',
		'posts_per_page' 	=> -1
	);

if( $atts['city'] != '' ) {

	$cities = explode( ',', $atts['city'] );
	
	$meta_query = array();
	
	if( !empty($cities) ) {
		foreach ($cities as $key => $city) {
			$meta_query[] = array(
					'key' 		=> 'cptwh_property_city',
					'value' 	=> strtolower(trim($city)),
					'compare' 	=> 'LIKE'
				);
		}
	} 
	$args['meta_query']['relation'] = 'OR';
	$args['meta_query'] = $meta_query;
}

$properties = new WP_Query( $args );

1.Here are the steps to do this.
2.Extract the attribute values. Like, I’ve used city attribute.
3.Now you have to check if users has assigned any value to City attribute. If there is no value we will not process the Meta Query.
4.In case we have found any value in the City. Lets, find the number of cities entered by using explode function.
5.Now parse the exploded string using foreach loop and assign values to a newly created array variable meta_query.
6.Now, after Array element use a ‘relation’ element for comparision method. Default value of ‘relation’ is ‘AND’. If in case you will not provide any value it will find the records which fall under the values. I’ve assigned value OR to this so that I can fetch all the Posts which have the City 1 and City 2 in its meta table.

Leave a Reply

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