Adding country tags automatically

I want to show country flags on post cards.My plan is showing flag icons with below code:

img src="/icons/?php echo $tagName; ?.png" /

However I dont know how can I add country tags to Wordpress.You know there are many many country on the world (If I am not wrong there are nearly 200 country based United Nations).Or maybe the country number of I will add as tag will be depend the icon set which I will find.So How can I add country tags automatically with code?

Topic template-tags count tags php theme-development Wordpress

Category Web


I'd recommend making use of this API: https://www.countryflags.io/.

You'll also need a list of countries and country codes. Download that here: https://gist.github.com/keeguon/2310008

Then, you can do something like this to register all of the countries to your custom post type's taxonomy. (you only really need to run this code once)

$countries_json = file_get_contents('/countries.json/');

$countries = json_decode($countries_json, true);

foreach ( $countries as $country ) {
    $term = $country->name;
    $taxonomy = YOUR_COUNTRY_TAXONOMY;
    $args = array(slug => $country->country_code);

    wp_insert_term( $term, $taxonomy, $args);
}

Now, all of the country names should be appearing under that taxonomy and you can assign whatever country you want to your post cards. So that when your looping through all your posts and rendering content you can check what country is selected by getting the terms using get_the_terms( int|WP_Post $post, string $taxonomy ).

When you have the terms for a post. You can render the country flag like this:

<img src="/icons/<?php echo $term->code; ?>.png" />

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.