Wordpress2个月前发布 SUYEONE
405 0 0

Due to the hierarchical structure of WordPress Databases, it often requires iterative retrieval when dealing with multiple levels. When dealing with a complex categorization system, it can be quite challenging to fetch top-level category information directly. Upon researching, I found that WordPress does not offer a built-in function for this purpose. Therefore, I created a simplified solution to fetch the top-level category information for an article in WordPress.

The category fetching functionality in WordPress can be broadly categorized into two types: one retrieves the categories associated with a specific post ID, and the other fetches detAIls based on a category ID. By leveraging these, we can achieve our desired outcome. Here’s the code:

/* Retrieve Top-Level Category Info */
function fanly_basic_Get_category_root($post_ID, $meta_key = ‘TERM_ID’) {
$categories = get_the_category($post_ID)[0] ?? null;

while (isset($categories->category_parent)) {
$categories = get_category($categories->category_parent);

return $categories->$meta_key ?? ”;

From an optimization standpoint, overly deep URLs for post categories are not recommended. When using ‘category’ as the permalink structure in WordPress, it’s advisable to keep the category hierarchy as shallow as possible – ideally, just one level. Although it’s possible to use a second-level category, WordPress is primarily designed to handle only one level effectively. For personal usage, a single level should suffice, and if you opt for a two-level hierarchy, WordPress will mainly resolve at the first level.

© 版权声明