Home  >  Article  >  CMS Tutorial  >  How to get category directory in wordpress

How to get category directory in wordpress

藏色散人
藏色散人Original
2023-02-20 09:54:313282browse

How wordpress obtains the category directory: 1. Use the "get_the_category()" function to obtain the category information of the current article based on the article ID; 2. Use the "get_category()" function to obtain the category information based on the category ID Just get the category directory information.

How to get category directory in wordpress

The operating environment of this tutorial: Windows 10 system, WordPress version 6.1, DELL G3 computer

How to get the category directory for wordpress?

Due to the WordPress database structure design, sometimes it is necessary to obtain the information in a loop if there are more levels. If there are too many levels of classification directories, it really takes a lot of effort to obtain the information of the top directory. , and I also checked that WordPress does not provide relevant functions to obtain, so I simply encapsulated a WordPress to obtain the top-level directory information of the directory where the article is located.

WordPress's functions for obtaining categories can be divided into two major categories. One is to obtain the category information of the current article based on the article ID get_the_category(), and the other is to obtain the category information based on the category ID class get_category( ). I can use these two functions to achieve the function I want. The code is as follows:

/* 获取顶级分类目录信息
 * term_id name slug description
 * cat_ID category_description cat_name
 */
function fanly_basic_get_category_root( $pid, $meta='term_id' ){
$cats = get_the_category($pid)[0] ?? '';
while(@$cats->category_parent){ //有父分类时循环
$cats = get_category(@$cats->category_parent);
}
return $cats->$meta ?? '';
}

In fact, from an optimization point of view, it is not good if the URL depth of the article directory is too long, but for WordPress, category is used When making fixed links, the category directory should be embedded in as few layers as possible. Of course, one layer is enough for me personally. If a second-level directory is used, then secondary development of WordPress can be used to fix only the first-level directory.

Recommended learning: "WordPress Tutorial"

The above is the detailed content of How to get category directory in wordpress. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn