Skip to main content

Command Palette

Search for a command to run...

The great category conundrum.

Published
3 min readView as Markdown
S
Hello there! I am a seasoned senior software engineer, currently working at Ropardo, a prominent company based in Sibiu. My expertise lies in frontend development, which is where I mainly focus my work efforts. In the past, I have contributed to various projects for SmartBill, spearheaded a community of over 1.5 million members, and developed exceptional products for Koding, a San Francisco-based company. Furthermore, I have built and helped with the development of presentation websites and online stores for small businesses at Sensmedia. As a passionate advocate of the open-source movement, I am always on the lookout for fresh and innovative projects to work on. Currently, I am dedicated to constructing a local web community called @SibiuWebMeetup in Sibiu. If you need to contact me, please don't hesitate to drop me an email at hello@stefancosma.xyz or look me up on most social media platforms using the handle @stefanbc. On a personal note, I am an avid comics enthusiast and amateur photographer, and you can often find me indulging in these hobbies in my free time. Please note that I usually respond to messages within 1-2 business days.

It all started on one December-ish looking morning. It was the year of our lord 2013 and the snow was nowhere to be found, keeping that mind, there was a slight smell of bugs in the air. You know the type I'm talking about? The ones that don't let you sleep at night and make you go to bed at 2AM. Those kind of bugs. Thankfully the so-called "bug", I am going to describe in the rows below, is not one of those.

This was a simple one. One that started from the bottom, from the inner core of all that is holly and peaceful. So what is then?

How in the world do you get a category that has a certain parent for a post (either specific post or the current one)? Yes it's a simple question but if you close enough you'll see that none of the WordPress inner core function offer a direct solution.

Well after a long quest on the realm of the interwebs I came across many that claimed they had the answer but all of them were shams. In the end I managed to gather enough knowledge to come up with a slight deviation of a solution I found along my voyage. You can check it out below.

// Save the names and the IDs of the parent categories you want in an array
$parents = array(
   'NAME_OF_PARENT_CATEGORY' => ID_OF_THE_CATEGORY
);
// The the categories of the current post
$categories = get_the_terms( $post->ID, 'category' );

// Output parent categories and their children
foreach( $parents as $parent_name => $parent_id ):
    // Output the parent name
    echo $parent_name;
    // Create an array to hold the children
    $links = array();
    foreach( $categories as $category ):
        if( $parent_id == $category->parent ):
            // Put the category link in the array
            $links[] = '<a href="' . get_term_link( $category ) . '">' . $category->name . '</a>';
        endif;
    endforeach;
    // Join everything and output it
    echo join( ', ', $links );
 endforeach;

Ok, now let's try to understand this snippet of code. For the sake of this tutorial lets say we have a review website that covers places to eat, places to drink and places to have fun. Each one of those categories is a general one, and we have a business that is categorized with restaurants (that has the parent, places to eat) and others, like location and availability, that have different parents. So we have 3 categories on the same post and we need to output only the one that belongs to places to eat.

  1. First we create an array for the parents, because maybe we have multiple categories and we need the children for all of them.
  2. Ok, after that we get all the categories of the current post (eg. restaurant, location, availability).
  3. We go through the parent categories that we set up on step one (eg. places to eat, places to drink, places to have fun).
  4. While we are doing that we build another array where we will keep the children.
  5. The next step is to go through all the categories of the current post and check if the parent of each category matches one that is available in the array we created at step one. If we find one than we add it to the array of children.
  6. Joining everything is the second to last step that we need to do.
  7. Finally we can output our result.

And that's it. Simple, right? I hope you enjoyed this short, simple tutorial.

Let me know if you found another solution in the comments.

Until next time, code long and prosper!

Stefan

More from this blog

S

Stefan Cosma

50 posts

Lead Software Developer | Community builder @ Sibiu Web Meetup | Co-organiser @ Friendly.rb | Hackathon Coordinator