This is How to Sort Terms in a Custom Taxonomy by Parent-Child Relationships in WordPress
Organizing content with custom taxonomies is a powerful feature of WordPress, allowing you to group and categorize your posts, pages, and other content types in a structured way. However, when it comes to displaying these custom taxonomy terms, you may encounter challenges in ensuring the terms are displayed in the correct parent-child order.
In this article, we'll explore a step-by-step solution to sort terms in a custom taxonomy by their parent-child relationships in WordPress, using the get_terms()
function.
Understanding the get_terms() Function
The get_terms()
function is a core WordPress function that allows you to retrieve a list of terms from a given taxonomy. By default, the terms are sorted alphabetically by their name. However, if you want to sort the terms by their parent-child structure, you'll need to use additional arguments.
Here's the basic syntax for the get_terms()
function:
$terms = get_terms([
'taxonomy' => 'your_custom_taxonomy',
'hide_empty' => false,
'orderby' => 'name',
'parent' => false,
]);
Let's break down the arguments used in this example:
'taxonomy' => 'your_custom_taxonomy'
: This specifies the custom taxonomy you want to retrieve terms from.
'hide_empty' => false
: This ensures that the function will return all terms, even if they have no associated posts.
'orderby' => 'name'
: This sorts the terms alphabetically by their name.
'parent' => false
: This tells the function to only retrieve top-level (parent) terms, and not their child terms.
To retrieve the child terms and sort them correctly by their parent-child structure, we'll need to use a more complex approach.
Sorting Terms by Parent-Child Relationships
To sort terms in a custom taxonomy by their parent-child relationships, we can use the 'order'
and 'orderby'
arguments in the get_terms()
function, along with a custom callback function to handle the sorting.
Here's the code to achieve this:
function sort_terms_by_parent($terms, $taxonomy) {
$sorted_terms = array();
// Separate terms into two arrays: parents and children
$parents = array();
$children = array();
foreach ($terms as $term) {
if ($term->parent == 0) {
$parents[] = $term;
} else {
$children[] = $term;
}
}
// Sort the parent terms
usort($parents, function($a, $b) {
return strcasecmp($a->name, $b->name);
});
// Attach the child terms to their respective parents
foreach ($parents as $parent) {
$sorted_terms[] = $parent;
$parent_id = $parent->term_id;
foreach ($children as $key => $child) {
if ($child->parent == $parent_id) {
$sorted_terms[] = $child;
unset($children[$key]);
}
}
}
// Add any remaining child terms (orphans)
foreach ($children as $child) {
$sorted_terms[] = $child;
}
return $sorted_terms;
}
$terms = get_terms([
'taxonomy' => 'download_category',
'hide_empty' => false,
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0,
]);
$sorted_terms = sort_terms_by_parent($terms, 'download_category');
Let's break down the code step by step:
- The
sort_terms_by_parent()
function takes two arguments: $terms
(the array of terms returned by get_terms()
) and $taxonomy
(the name of the custom taxonomy).
- We start by separating the terms into two arrays:
$parents
(for top-level terms) and $children
(for child terms).
- We then sort the
$parents
array alphabetically using the usort()
function and a custom callback.
- Next, we loop through the
$parents
array and attach the corresponding $children
terms to their respective parent terms, creating a hierarchical structure.
- Finally, we add any remaining
$children
terms (orphans) to the $sorted_terms
array.
- The
$sorted_terms
array is then returned, containing the terms sorted by their parent-child relationships.
In the second part of the code, we call the get_terms()
function to retrieve the terms for the 'download_category'
taxonomy, and then pass the resulting $terms
array to the sort_terms_by_parent()
function to sort them accordingly.
By using this approach, you can ensure that your custom taxonomy terms are displayed in the correct hierarchical order, with child terms properly nested under their respective parent terms.
Utilizing the Sorted Terms
Now that you have the sorted terms, you can use them in various ways throughout your WordPress site. Here are a few examples:
-
Display the Terms in a Hierarchical List:
<ul>
<?php foreach ($sorted_terms as $term) : ?>
<li>
<?php echo $term->name; ?>
<?php if (!empty($term->children)) : ?>
<ul>
<?php foreach ($term->children as $child) : ?>
<li><?php echo $child->name; ?></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
-
Use the Sorted Terms in a Dropdown Menu:
<select name="download_category">
<option value="">Select a category</option>
<?php foreach ($sorted_terms as $term) : ?>
<option value="<?php echo $term->slug; ?>">
<?php echo str_repeat(' ', substr_count($term->name, '-')) . $term->name; ?>
</option>
<?php endforeach; ?>
</select>
-
Integrate the Sorted Terms into a Widget or Plugin:
// In a widget or plugin
$sorted_terms = sort_terms_by_parent(get_terms('download_category'), 'download_category');
// Use the $sorted_terms array to display the terms in your widget or plugin
By using the sorted terms, you can ensure that your custom taxonomy is displayed in a clear and organized manner, providing a better user experience for your website visitors.
Conclusion
Sorting terms in a custom taxonomy by their parent-child relationships is an important task when working with WordPress. By using the get_terms()
function and a custom sorting function, you can ensure that your taxonomy terms are displayed in the correct hierarchical order, making it easier for users to navigate and understand the content on your website.
Remember, this solution can be applied to any custom taxonomy, not just the 'download_category'
example used in this article. Adapt the code as needed to fit your specific use case.
If you're looking for a way to optimize your website's conversion rates and user experience, consider trying Flowpoint.ai. Flowpoint's AI-powered analytics can help you identify technical, UX, and content-related issues that may be impacting your website's performance, and generate recommendations to fix them
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.