Backend Development
PHP Tutorial
WordPress Custom Post Type: Implementation Guide for Filtering by Category and Displaying Category Descriptions
WordPress Custom Post Type: Implementation Guide for Filtering by Category and Displaying Category Descriptions

This tutorial details how to implement filtering by category for custom post types in WordPress and display the description information of the selected category at the same time. Through step-by-step guidance, it demonstrates how to use get_terms() to obtain category terms, and combine it with the tax_query parameter of WP_Query to organize content, ensuring that the name and description of each category can be clearly presented before displaying related articles, thereby improving user experience and content organization structure.
In WordPress development, we often encounter the need to create a category filter view for a custom post type (Custom Post Type, CPT). A common scenario is that when users filter articles by a specific category (i.e., Custom Taxonomy), they want to not only see a list of articles under that category, but also display detailed description information of the category. This helps users better understand classified content and improves the navigation and information richness of the website.
Core implementation ideas
To achieve this functionality, we can’t just rely on WordPress’s main query or a simple post loop. The core idea is:
- First obtain all relevant classification terms (Terms). For example, if your custom post type is "Portfolio" and the taxonomy is "Portfolio Category", then we need to get all the terms for "Portfolio Category".
- Iterate over each taxonomy term. During the traversal process, we can access the name, description and other information of each term.
- Execute a separate WP_Query for each taxonomy term. This query will be specifically used to retrieve custom articles belonging to the currently traversed taxonomy term.
Through this "categories first, articles later" structure, we can display the name and description of a specific category before displaying the articles in that category.
Detailed implementation steps and code examples
Below is an example of PHP code that implements the above functionality, which you can place in your theme template file (such as archive-{post_type}.php, page-templates/your-template.php or any page you wish to display this content).
<?php // 1. Get all terms for a specified custom taxonomy // Replace 'portfolio_category' with your actual taxonomy name $terms = get_terms('portfolio_category', array(
'hide_empty' => false, // Display even if there are no articles under the category));
// 2. Check whether the terms are successfully obtained and there are no WordPress errors if (!is_wp_error($terms) && !empty($terms)) :
// 3. Traverse each classification term foreach ($terms as $term):
?>
<div class="category-section">
<div class="row category-header">
<div class="col-lg-12">
<!-- Display category name -->
<h2>
<?php echo esc_html($term->name); ?></h2>
<?php // 4. Display category description (if exists)
if (!empty($term->description)) :
?>
<p class="category-description"><?php echo esc_html($term->description); ?></p>
<?php endif; ?>
</div>
</div>
<div class="row category-posts">
<?php // 5. Construct a new WP_Query query for the current term $args = [
'post_type' => 'YOUR_CUSTOM_POST_TYPE', // **IMPORTANT: Please replace with your custom post type name**
'post_status' => 'publish', // Only query published articles 'posts_per_page' => -1, // Display all articles under the current category, or specify a positive integer 'tax_query' => [ // Tax category query parameters, used to filter articles by category [
'taxonomy' => 'portfolio_category', // **IMPORTANT: Please replace with your taxonomy name**
'field' => 'term_id', // Query based on term ID 'terms' => $term->term_id // Currently traversed term ID
]
]
];
$query = new WP_Query($args);
// 6. Check whether there are articles that match the query conditions of the current category if ($query->have_posts()):
// 7. Loop through and display posts while ($query->have_posts()):
$query->the_post(); // Set current post data?>
<div class="col-lg-4 post-item">
<a href="<?php%20the_permalink();%20?>">
<?php // Display the article's featured image (if it exists)
if (has_post_thumbnail()) :
?>
<img src="<?php%20the_post_thumbnail_url('medium');%20?>" alt="<?php the_title_attribute(); ?>" class="img-fluid">
<?php endif; ?>
<h3><?php the_title(); ?></h3>
</a>
</div>
<?php endwhile;
// 8. Reset the post data to ensure that the main query is not affected wp_reset_postdata();
else :
// What if there are no articles in the current category?>
<div class="col-lg-12">
<p>There are no articles under the current category "<?php echo esc_html($term->name); ?>". </p>
</div>
<?php endif; // End $query->have_posts() check?>
</div> <!-- .row category-posts -->
</div> <!-- .category-section -->
<?php endforeach; // End foreach ($terms as $term) loop else:
// What if no categories are found?>
<p>No categories found. </p>
<?php endif; //End!is_wp_error($terms) check?>
Code analysis and precautions
-
get_terms('portfolio_category', array('hide_empty' => false)) :
- get_terms() is a WordPress function used to get all terms for a specified taxonomy.
- The first parameter 'portfolio_category' must be replaced with the name of the custom taxonomy you are actually using.
- The 'hide_empty' => false parameter ensures that a category will be displayed even if there are currently no associated articles in it. If you only want to display categories with articles, you can set it to true.
-
foreach ($terms as $term) :
- This loop iterates through each taxonomy term object returned by get_terms(). Inside the loop, the $term variable represents the current taxonomy term and you can access its properties such as $term->name (name), $term->description (description), $term->term_id (ID), $term->slug (alias), etc.
-
echo esc_html($term->name); and echo esc_html($term->description); :
- esc_html() is a security function of WordPress, used to escape the output HTML content to prevent cross-site scripting attacks (XSS). Recommended to be used when any user input or content obtained from the database is output to the page.
-
WP_Query parameters ($args) :
- 'post_type' => 'YOUR_CUSTOM_POST_TYPE': Be sure to replace this with the name of the custom post type you registered.
- 'posts_per_page' => -1: means to get all articles that meet the conditions. If you want to limit the number of articles displayed under each category, you can set it to a positive integer, such as 5.
- 'tax_query': This is the key parameter to implement filtering by category.
- 'taxonomy' => 'portfolio_category': Again, this should be the name of your taxonomy.
- 'field' => 'term_id': Specifies which field of the term to match. 'term_id' is the most common and recommended way.
- 'terms' => $term->term_id: Pass the ID of the currently looped classification term to the query to ensure that only articles belonging to this term are obtained.
-
wp_reset_postdata() :
- wp_reset_postdata() is always called after the custom WP_Query loop (while ($query->have_posts()) : $query->the_post(); ... endwhile;) ends. This will restore the global $post variable to the state of the main query (if there is one), preventing unintended effects on WordPress loops and template tags in other parts of the page.
-
Error handling and empty status :
- The code includes checks for whether get_terms() returns an error (!is_wp_error($terms)) and whether it is empty (!empty($terms)).
- At the same time, each WP_Query is also checked whether there are articles ($query->have_posts()), and corresponding prompt information is displayed when there are no articles, which improves the user experience.
Summarize
With the above method, you can create a clear and organized display page for custom post types in WordPress, where posts are grouped according to the categories they belong to, and the name and description of each category are presented before the post list. This structure not only helps organize and manage website content, but also significantly improves visitors' understanding and navigation efficiency of the content. Please replace the placeholders in the code with your actual custom post type and taxonomy names, and adjust the HTML structure and CSS styles as needed to match your site design.
The above is the detailed content of WordPress Custom Post Type: Implementation Guide for Filtering by Category and Displaying Category Descriptions. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20522
7
13634
4
Instantiation mechanism and reflection application of PHP attributes
Mar 13, 2026 pm 12:27 PM
PHP properties do not automatically instantiate their class constructors when declared. They are essentially metadata attached to code elements and need to be explicitly read and instantiated through PHP's reflection API in order to trigger the execution of their constructors. Understanding this mechanism is critical to correctly utilizing properties to implement advanced functionality such as framework routing, validation, or ORM mapping.
PHP gRPC client JWT authentication practice guide
Mar 14, 2026 pm 01:00 PM
This article details how to correctly configure JWT (JSON Web Token) for authentication in the PHP gRPC client. The core is to set the request metadata in the standard Authorization: Bearer format through the update_metadata callback function to ensure that the server can correctly parse and verify the client's identity, thereby avoiding common authentication errors.
How to batch extract the values of all keys with the same name (such as 'id') in a JSON object in PHP
Mar 14, 2026 pm 12:42 PM
This article explains in detail how to use json_decode() and array_column() to efficiently extract all values of specified keys (such as id) in nested JSON data at all levels, avoiding manual traversal and taking into account performance and readability.
How to display hospital/center name instead of ID in patient query results
Mar 13, 2026 pm 12:45 PM
This article explains in detail how to use SQL table connections to replace the originally displayed hospital ID (h_id) with the corresponding hospital or center name when querying patient data to improve data readability and user experience.
PHP runtime getting and monitoring script maximum memory limit (bytes)
Apr 01, 2026 am 06:42 AM
This article aims to guide PHP developers on how to accurately obtain the maximum memory limit (in bytes) of a script at runtime, and combine it with real-time memory usage for effective monitoring. By parsing the memory_limit configuration string and using built-in functions, an early warning mechanism for memory consumption is implemented to avoid fatal errors caused by memory overflow.
How to append corresponding value to the end of each subarray of PHP array
Mar 14, 2026 pm 12:51 PM
This article describes how to append the values of a one-dimensional index array to the end of each sub-array of another two-dimensional array in order, solving alignment problems caused by index offsets (such as $array2 starting from key 1), and providing a safe and readable implementation solution.
Tutorial on flattening nested arrays into a single array in PHP
Mar 13, 2026 am 02:57 AM
This tutorial details how to flatten a nested array structure containing multiple sub-arrays into a single array in PHP. This can be achieved efficiently and concisely by utilizing PHP's array_merge function combined with the array unpacking operator (...) to extract all internal elements into a top-level array, suitable for processing collections or grouped data.
The reason why explode() returns nested arrays in PHP and its correct usage
Mar 14, 2026 pm 12:39 PM
explode() itself returns a one-dimensional array, but due to misuse of the array append syntax $myarray[] = ..., the result is wrapped into additional levels, forming an "array of arrays"; the correction method is to assign values directly instead of appending.





