How to Get the Category and Subcategory of a Custom Post Type as a Nested Array in WordPress
As a WordPress developer, you may have encountered the challenge of retrieving the category and subcategory of a custom post type as a nested array. This information is crucial for organizing your content, improving navigation, and enhancing the overall user experience on your website.
Unfortunately, the default WordPress functions don't provide a straightforward way to achieve this. However, with a bit of custom coding, you can easily overcome this obstacle and unlock the power of nested taxonomies for your custom post types.
In this article, we'll walk you through the step-by-step process of getting the category and subcategory of a custom post type as a nested array in WordPress. By the end of this guide, you'll have a robust solution that you can integrate into your WordPress projects.
Understanding the Problem
WordPress's built-in taxonomies, such as categories and tags, are designed to work with the default post type. However, when you introduce custom post types, the process of retrieving the associated taxonomies becomes more complex.
The standard WordPress functions, like get_the_category()
and get_the_terms()
, work well for the default post type, but they don't provide the nested structure you might need for custom post types.
To illustrate the problem, let's say you have a custom post type called "Products" and you've set up a taxonomy called "Product Categories" with both parent and child categories. When you try to retrieve the category and subcategory information for a specific product, you might end up with a flat array that doesn't reflect the hierarchical structure of your taxonomy.
The Solution: Nested Array for Custom Post Type Categories
To get the category and subcategory of a custom post type as a nested array, we'll need to use a custom function that leverages the WordPress get_the_terms()
function and recursively builds the desired data structure.
Here's the step-by-step process:
-
Create a Custom Function:
function get_custom_post_type_categories($post_id, $taxonomy = 'category') {
$terms = get_the_terms($post_id, $taxonomy);
$categories = array();
if (!empty($terms)) {
foreach ($terms as $term) {
if (empty($term->parent)) {
$categories[$term->term_id] = array(
'id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
'children' => get_custom_post_type_children($terms, $term->term_id)
);
}
}
}
return $categories;
}
-
Create a Helper Function to Retrieve Children Terms:
function get_custom_post_type_children($terms, $parent_id) {
$children = array();
foreach ($terms as $term) {
if ($term->parent == $parent_id) {
$children[$term->term_id] = array(
'id' => $term->term_id,
'name' => $term->name,
'slug' => $term->slug,
'children' => get_custom_post_type_children($terms, $term->term_id)
);
}
}
return $children;
}
-
Usage Example:
$post_id = 123; // Replace with your custom post type ID
$categories = get_custom_post_type_categories($post_id, 'product_category');
// The $categories variable now contains a nested array of categories and subcategories
print_r($categories);
Let's break down the code:
-
The get_custom_post_type_categories()
function takes two parameters: the post ID and the taxonomy name (default is 'category'). This function retrieves all the terms associated with the given post ID and taxonomy.
-
The function then loops through the terms and checks if the current term has a parent. If not, it means the term is a top-level category, and we add it to the $categories
array.
-
For each top-level category, we call the get_custom_post_type_children()
function, which recursively traverses the terms and builds the nested array of subcategories.
-
The get_custom_post_type_children()
function takes the list of terms and the parent ID as parameters. It loops through the terms and checks if the current term's parent ID matches the given parent ID. If so, it adds the term to the $children
array and recursively calls itself to retrieve any further subcategories.
-
Finally, the get_custom_post_type_categories()
function returns the $categories
array, which now contains the nested structure of categories and subcategories.
The resulting $categories
array will look something like this:
Array(
[123] => Array(
'id' => 123,
'name' => 'Top-Level Category',
'slug' => 'top-level-category',
'children' => Array(
[456] => Array(
'id' => 456,
'name' => 'Subcategory 1',
'slug' => 'subcategory-1',
'children' => Array()
),
[789] => Array(
'id' => 789,
'name' => 'Subcategory 2',
'slug' => 'subcategory-2',
'children' => Array(
[101112] => Array(
'id' => 101112,
'name' => 'Sub-Subcategory',
'slug' => 'sub-subcategory',
'children' => Array()
)
)
)
)
)
)
This nested array structure allows you to easily access and display the category and subcategory information for your custom post type, providing a better user experience and enhancing the overall organization of your website's content.
Optimizing for SEO and Performance
To further optimize your website's performance and SEO, consider the following additional steps:
-
Caching: To avoid unnecessary database queries, you can cache the results of the get_custom_post_type_categories()
function using a caching plugin or a custom caching mechanism. This will improve your website's loading speed and reduce the server load.
-
Breadcrumb Navigation: Utilize the nested category information to display a breadcrumb navigation system on your custom post type pages. This helps users understand the content hierarchy and improves the overall user experience.
-
SEO-Friendly URLs: When displaying the custom post type content, you can use the category and subcategory slugs to create SEO-friendly URLs, which can boost your website's visibility in search engine results.
-
Sitemap Generation: Incorporate the nested category structure into your WordPress sitemap generation process, making it easier for search engines to crawl and index your website's content.
-
Structured Data: Use the category and subcategory information to generate structured data, such as schema.org markup, for your custom post type pages. This can enhance your website's visibility in search engine results and provide additional context about your content.
By implementing these optimization techniques, you can leverage the nested category structure to improve the overall user experience, search engine optimization, and performance of your WordPress-powered website.
Flowpoint.ai can help you identify all the technical errors that are impacting conversion rates on your website and directly generate recommendations to fix them, including optimizing your website's taxonomy structure for better user experience and SEO.
Get a Free AI Website Audit
Automatically identify UX and content issues affecting your conversion rates with Flowpoint's comprehensive AI-driven website audit.