Categories
Technology

Finding Post Based 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.

Finding Post Based on Post Meta Value in WP Query

April 16, 2021
Technology
Admin

Recently I was working on a Custom Post Type plugin under the banner of RND Experts, where the user will enter the name of the city and the field will get saved in the wp_post_meta table. The client has requested to create a shortcode where we can filter Posts on the basis of Single city or Multiple comma-separated 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 have assigned any value to the 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. Let, ‘s find the number of cities entered by using the explode function.


5. Now parse the exploded string using the for each loop and assign values to a newly created array variable meta_query.


6. Now, after the Array element use a ‘relation’ element for the comparison method. The default value of ‘relation’ is ‘AND’. If in case you do 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 that have City 1 and City 2 in its meta table.

Leave a Reply

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