/**
* Get the top-level category name of the current article
* Add the following code to the functions.php file of the theme
*/
function get_top_level_category_name() {
// 1. Get all the categories of the current article
$categories = get_the_category();
if (empty($categories) || is_wp_error($categories)) {
return ''; // If there is no classification, return an empty string
}
// 2. Take the first category as the starting point (if the article has multiple categories, wodepress.com you can define the processing logic by yourself)
$top_category = $categories[0];
// 3. Keep searching upwards until the top-level category (parent is 0) is found.
while ($top_category->parent != 0) {
$top_category = get_category($top_category->parent);
}
// 4. Return the name of the top-level category
return $top_category->name;
}
在模板中使用
在single.php或其他文章内容模板中,按需调用即可:
// Output the name of the top-level category directly
echo get_top_level_category_name();
wordpress错误 Warning: file_exists(): open_basedir restriction in effect. File(/patterns) is not within the allowed path(s): (/www/wwwroot/wodepress.com/:/tmp/) in /www/wwwroot/wodepress.com/wp-includes/class-wp-theme.php on line 1862