Sort custom field by post

Ok it is pretty simple. Every post of my blog has a specific country. So i have the custom field country and then, when i write the article i add: japan, argentina, usa, italy etc. to the post. Now in home i like to have a box like that:

Post By Country:

Read More

Japan (130 posts)
Usa (104 posts)
Argentina (90 posts)
Italy (46 posts)
Uk (23 post)

etc, etc. Then, be able to click on a contry and have all the post from that country. I’m not so familiar with php queries, can u help me?

Tnx a lot.

Related posts

Leave a Reply

2 comments

  1. Here’s a loop that pulls all your post with the custom field key “Country”…

    <?php
    $countryPosts = new WP_Query();
    $countryPosts->query('meta_key=country');
    ?>
    <?php while ($countryPosts->have_posts()) : $countryPosts->the_post(); ?>
    CONTENT STUFF HERE
    <?php endwhile; ?>
    

    Now to order that you can add order=ASC or order=DESC so this line reads:

    $countryPosts->query('meta_key=country&order=ASC');

    Here’s the loop that will show all the post that have the custom field filled out for a specific country, in this example, Japan:

    <?php
    $countryPosts = new WP_Query();
    $countryPosts->query('meta_key=country&meta_value=japan');
    ?>
    <?php while ($countryPosts->have_posts()) : $countryPosts->the_post(); ?>
    CONTENT STUFF HERE
    <?php endwhile; ?>
    

    Update: After re-reading your question I realized I may not fully understand what you are trying to do correctly. The above code will let you display posts from a specific country but it won’t show that “archives” type navigation box. From the sound of it, you may want to create a custom taxonomy for countries rather than using a custom field. This will make it a lot easier to interact with the posts based on the Country.