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?
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?
Share Improve this question asked Jan 20, 2020 at 11:24 Faruk rızaFaruk rıza 982 silver badges11 bronze badges 4- Are post cards a post type? Do you have a country taxonomy? – Tom J Nowell ♦ Commented Jan 20, 2020 at 11:43
- @TomJNowell custom post type.no taxonomy – Faruk rıza Commented Jan 20, 2020 at 11:52
- Ooh, so these are not tags, they are posts? That's an important piece of information! You should edit your question to talk about country posts, not country tags – Tom J Nowell ♦ Commented Jan 20, 2020 at 12:19
- my sorry, it is taxonomy for custom post type. – Faruk rıza Commented Jan 20, 2020 at 12:42
1 Answer
Reset to default 1I'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/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" />