0

I have two custom post types: Country and City.

Country

There is just a text field to fill with its name.

enter image description here

City

I have a text field for city's name and also a select with all the countries that was added in the other custom post type.

enter image description here

My question is, how to get for each city, its own country?

To retrieve the cities I'm using:

$args = array (
  'post_type' => 'cities'
);
$query = new WP_Query($args);

In this result of cities, I don't have any information related to the country that I select in the admin area.

Thanks!

2

If in a country looking for cities

$args = array (
    'post_type' => 'cities',
    'meta_key' => 'country',
    'meta_value' => get_the_ID()
);

This assumes that the "Country > Name* > [drop down]" you screenshot saves that the selected value using post_meta and is saving the country's post ID. (If it does not please adjust or specify).

UPDATE

To list cities, and retrieve their country_name, assuming the dropdown is just storing the post_title of the country, you could do:

$cities = get_posts(array (
    'post_type' => 'cities',
    'numberposts' => '-1',
));
foreach ($cities as $city) {
    $country_name = get_post_meta($city->ID,'country_name',true);
    // to get the full country, if country_name is just the post title (and not ID) you could do
    # $country = get_page_by_title( $country_name, 'object', 'country' );
    echo "<pre>City: {$city->post_title} is in country: {$country_name}</pre>":
}
3
  • Thanks for your comment David. This example that you wrote. I'm trying to get the city list, and for each city, get the country that I select in the admin area. The country is a custom type post as well, and the field name is country_name. This meta_key is related to the field name?? – Italo Borges Dec 20 '17 at 19:05
  • 1
    I'm unsure if your setup has the country_name saved as a meta value, and wether it saves as a string (the country name) or an ID - but that's normally how it's setup - can you please provide more info about how you've setup country_name within a city post type. Regardless, I've updated my post to list all cities with their respective country. – David Sword Dec 20 '17 at 19:20
  • David, it worked. With your updated code, I could get the country ID. country_name is the field name for my post_object. I should change just for country, will make more sense. Thanks very much!!! Now I will dig deeper to understand the query because I will need to create more complex queries. Thanks! – Italo Borges Dec 21 '17 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.