How to Display a List of Primary Tags in Ghost
I came across this Ghost Forum post about showing a list of primary tags. There is no native Ghost helper, but here is a workaround.
Loop through posts. Then, loop through tags for each post and limit the tags to one, which will be the primary tag.
{{#get 'posts' include='tags'}}
{{#foreach posts}}
{{#foreach tags limit='1'}}
<li class='item' data-slug='{{slug}}'>
<a href='{{ url }}'>{{ name }}</a>
</li>
{{/foreach}}
{{/foreach}}
{{/get}}
The primary tags from the fetched posts will now be visible, with duplicates. The query uses Ghost’s default limit of 15 posts. It does not cover every post on a larger site. Use the get helper’s limit and page options to fetch more posts. With some JavaScript, we can clean the duplicated ones.
<script>
var finalList = { },
elements = document.querySelectorAll('.item');
elements.forEach( element => {
if (finalList[element.dataset.slug]) {
element.style.display= 'none';
} else {
finalList[element.dataset.slug] = true;
}
});
</script>
jQuery version.
Make sure to load jQuery before that JS code.
<script>
$(document).ready(function() {
var found = {};
$('.item').each(function() {
var $this = $(this);
if(found[$this.attr('data-slug')]) {
$this.remove();
} else {
found[$this.attr('data-slug')] = true;
}
});
});
</script>
JS code credit: https://mijokristo.com/remove-duplicate-elements-from-list-by-value-with-jquery/
Hopefully, you find this helpful.
More from the Blog
Latest Ghost Themes
Arish
For visual magazines that lead with photography, film, and selected stories.
Siwa
A personal publication that introduces the writer before inviting readers into the stories.
Hanoi
An image-led magazine for creative stories, rich navigation, and long-form reading.
Taba
A newsroom front page for coverage across topics, video, and story formats.
Marsa
A flexible publication homepage for featured stories, topics, and newsletters.
Hakone
For writers who want readers to browse complete posts on the homepage.