i have different CPT ( hotel, market, city, etc… )
My relationship field is used to link CPT to cities (CITY).
Now in a page ( hotel page ) i want to link “other hotels in same city”.
how can i make my query ? I know how to do a query by ID with the ID of actual page, but what i need is :
$city = get_field(‘contact_city’); $query = display all hotels with contact_city as $city
But i didn’t find any solution.
i have different CPT ( hotel, market, city, etc… )
My relationship field is used to link CPT to cities (CITY).
Now in a page ( hotel page ) i want to link “other hotels in same city”.
how can i make my query ? I know how to do a query by ID with the ID of actual page, but what i need is :
$city = get_field(‘contact_city’); $query = display all hotels with contact_city as $city
But i didn’t find any solution.
Share Improve this question asked Apr 24, 2019 at 9:20 GregoryGregory 6025 silver badges20 bronze badges2 Answers
Reset to default 0If only 1 value in relation field :
$city_id = $bnb_ville[0]->ID;
if it could be more than 1 value :
$city_id = [];
foreach ($var as $post) {
$city_id[] = $post->ID;
}
$bnb_ville is the variable for get_field() !
Creating query you must use the meta_query
parameter.
Your relationship field is saved in DB as serialized array,
therefore, in the meta_query
parameter you should use the LIKE
operator.
Assuming that the CTP hotel
has only one city
assigned, the query would look like this:
$cities = get_field('contact_city');
if ( is_array($cities) && count($cities) ) {
$city_id = current($cities)->ID;
$args = [
'post_type' => 'hotel',
'meta_query' => [
'key' => 'contact_city',
'value' => '"' . $city_id . '"',
'compare' => 'LIKE',
],
// ...
];
$my_query = new WP_Query( $args );
}
If post hotel
has several city
assigned, and you want to display links to hotels from all locations assigned to the currently viewed hotel, meta_query
will change as follows:
$args = [
'post_type' => 'hotel',
'meta_query' => [
'relation' => OR,
[ /* 'key', 'value', 'compare' */ ],
[ /* 'key', 'value', 'compare' */ ],
],
Sample code:
$meta_query = [ 'relation' => 'OR' ];
foreach( $cities as $city )
{
$meta_query[] = [
'key' => 'contact_city',
'value' => '"' . $city->ID . '"',
'compare' => 'LIKE',
];
}
$args = [
'post_type' => 'hotel',
'meta_query' => $meta_query,
];
$my_query = new WP_Query( $args );