How to verify if blog post don’t have any categories in WordPress

In my current work I have to solve many problems for customers with WordPress websites. It’s common to see this scenario:

  • Website running a child theme based on Twenty something WP Theme
  • A thousand plugins installed, half active, half inactive
  • Patches all over functions.php
  • Custom plugins
  • A mess in the way they created .php files

And then they want to implement something which might not be that hard, but it takes 5 hours to find out where is this function calling, which hook is doing what, which file has the content of this nonsense piece of code, etc.

Today I had to face this situation: the customer has a website to display products, most of them are linked to a category, but some of them don’t, and they want to display a generic category under those products.

In order to fix this, I had to implement an if statement to check whether the post has a category or not, in case it has, leave the old code running to display the proper category, and if not, display a custom message with a link to the generic category. Bla bla.

This is the code that allowed me to do that:


$terms = get_the_term_list( $post->ID, 'categories', '<li class="item">', ' . ', '</li>' );

echo $terms;

echo '<li class="collection_item"><a href="#">Generic Title</a></li>';


I just had to use the get_the_term_list(); WP function explained here.

Published by Fernando Papaqui

Front end web developer working with Gatsby, JS, React, and WordPress. Mexico native.

Leave a comment

Your email address will not be published. Required fields are marked *