wp_list_categories()
云策文档标注
概述
wp_list_categories() 是 WordPress 核心函数,用于显示或检索分类的 HTML 列表。它支持丰富的参数配置,包括排序、层级显示、排除特定分类等,并可通过 Walker 类自定义输出结构。
关键要点
- 函数用于生成分类列表,默认输出为无序列表(ul),可配置为其他样式或返回字符串。
- 参数 $args 接受数组或字符串,控制行为如 echo、taxonomy、title_li、show_count、depth 等,默认值基于 get_categories() 和 WP_Term_Query。
- 默认行为包括:按名称升序排序、显示有文章的分类、使用 Walker_Category 渲染、当前分类添加 'current-cat' 类。
- 可通过参数调整输出,例如设置 style 为 'none' 移除列表标记,或使用 exclude 和 child_of 筛选分类。
- 函数返回 void(当 echo 为 true 时)或 HTML 字符串(当 echo 为 false 时),若 taxonomy 不存在则返回 false。
- 支持自定义分类法(taxonomy 参数),并可通过 walker 参数使用自定义 Walker 对象。
代码示例
// 显示分类列表,按名称排序,显示文章数量,排除 ID 为 10 的分类
wp_list_categories( array(
'orderby' => 'name',
'show_count' => true,
'exclude' => array( 10 )
) );
// 自定义分类法 'genre' 的列表,隐藏标题
$args = array(
'taxonomy' => 'genre',
'title_li' => ''
);
wp_list_categories( $args );注意事项
- 参数 $args 可继承 get_terms() 和 WP_Term_Query 的额外参数,如 meta_key 和 meta_value。
- 默认情况下,show_count 为 false,若启用会在分类名称后显示括号内的文章数量,可通过正则表达式移除括号。
- 使用 title_li 参数可设置或隐藏列表标题,设为空字符串可移除默认的 'Categories' 标题。
- CSS 类如 .cat-item、.current-cat 可用于样式定制,输出结构可通过 style 参数调整。
原文内容
Displays or retrieves the HTML list of categories.
Parameters
$argsarray|stringrequired-
Array of optional arguments. See get_categories() , get_terms() , and WP_Term_Query::__construct() for information on additional accepted arguments.
current_categoryint|int[]ID of category, or array of IDs of categories, that should get the'current-cat'class. Default 0.depthintCategory depth. Used for tab indentation. Default 0.echobool|intWhether to echo or return the generated markup. Accepts 0, 1, or their bool equivalents. Default 1.excludeint[]|stringArray or comma/space-separated string of term IDs to exclude.
If$hierarchicalis true, descendants of$excludeterms will also be excluded; see$exclude_tree. See get_terms() .
Default empty string.exclude_treeint[]|stringArray or comma/space-separated string of term IDs to exclude, along with their descendants. See get_terms() . Default empty string.feedstringText to use for the feed link. Default ‘Feed for all posts filed under [cat name]’.feed_imagestringURL of an image to use for the feed link. Default empty string.feed_typestringFeed type. Used to build feed link. See get_term_feed_link() .
Default empty string (default feed).hide_title_if_emptyboolWhether to hide the$title_lielement if there are no terms in the list. Default false (title will always be shown).separatorstringSeparator between links. Default<br />.show_countbool|intWhether to include post counts. Accepts 0, 1, or their bool equivalents.
Default 0.show_option_allstringText to display for showing all categories. Default empty string.show_option_nonestringText to display for the ‘no categories’ option.
Default ‘No categories’.stylestringThe style used to display the categories list. If'list', categories will be output as an unordered list. If left empty or another value, categories will be output separated by<br>tags. Default
'list'.taxonomystringName of the taxonomy to retrieve. Default'category'.title_listringText to use for the list title<li>element. Pass an empty string to disable. Default'Categories'.use_desc_for_titlebool|intWhether to use the category description as the title attribute.
Accepts 0, 1, or their bool equivalents. Default 0.walkerWalkerWalker object to use to build the output. Default empty which results in a Walker_Category instance being used.
More Arguments from get_categories( … $args )
Array or string of arguments. See WP_Term_Query::__construct() for information on accepted arguments.
Source
function wp_list_categories( $args = '' ) {
$defaults = array(
'child_of' => 0,
'current_category' => 0,
'depth' => 0,
'echo' => 1,
'exclude' => '',
'exclude_tree' => '',
'feed' => '',
'feed_image' => '',
'feed_type' => '',
'hide_empty' => 1,
'hide_title_if_empty' => false,
'hierarchical' => true,
'order' => 'ASC',
'orderby' => 'name',
'separator' => '<br />',
'show_count' => 0,
'show_option_all' => '',
'show_option_none' => __( 'No categories' ),
'style' => 'list',
'taxonomy' => 'category',
'title_li' => __( 'Categories' ),
'use_desc_for_title' => 0,
);
$parsed_args = wp_parse_args( $args, $defaults );
if ( ! isset( $parsed_args['pad_counts'] ) && $parsed_args['show_count'] && $parsed_args['hierarchical'] ) {
$parsed_args['pad_counts'] = true;
}
// Descendants of exclusions should be excluded too.
if ( $parsed_args['hierarchical'] ) {
$exclude_tree = array();
if ( $parsed_args['exclude_tree'] ) {
$exclude_tree = array_merge( $exclude_tree, wp_parse_id_list( $parsed_args['exclude_tree'] ) );
}
if ( $parsed_args['exclude'] ) {
$exclude_tree = array_merge( $exclude_tree, wp_parse_id_list( $parsed_args['exclude'] ) );
}
$parsed_args['exclude_tree'] = $exclude_tree;
$parsed_args['exclude'] = '';
}
if ( ! isset( $parsed_args['class'] ) ) {
$parsed_args['class'] = ( 'category' === $parsed_args['taxonomy'] ) ? 'categories' : $parsed_args['taxonomy'];
}
if ( ! taxonomy_exists( $parsed_args['taxonomy'] ) ) {
return false;
}
$show_option_all = $parsed_args['show_option_all'];
$show_option_none = $parsed_args['show_option_none'];
$categories = get_categories( $parsed_args );
$output = '';
if ( $parsed_args['title_li'] && 'list' === $parsed_args['style']
&& ( ! empty( $categories ) || ! $parsed_args['hide_title_if_empty'] )
) {
$output = '<li class="' . esc_attr( $parsed_args['class'] ) . '">' . $parsed_args['title_li'] . '<ul>';
}
if ( empty( $categories ) ) {
if ( ! empty( $show_option_none ) ) {
if ( 'list' === $parsed_args['style'] ) {
$output .= '<li class="cat-item-none">' . $show_option_none . '</li>';
} else {
$output .= $show_option_none;
}
}
} else {
if ( ! empty( $show_option_all ) ) {
$posts_page = '';
// For taxonomies that belong only to custom post types, point to a valid archive.
$taxonomy_object = get_taxonomy( $parsed_args['taxonomy'] );
if ( ! in_array( 'post', $taxonomy_object->object_type, true ) && ! in_array( 'page', $taxonomy_object->object_type, true ) ) {
foreach ( $taxonomy_object->object_type as $object_type ) {
$_object_type = get_post_type_object( $object_type );
// Grab the first one.
if ( ! empty( $_object_type->has_archive ) ) {
$posts_page = get_post_type_archive_link( $object_type );
break;
}
}
}
// Fallback for the 'All' link is the posts page.
if ( ! $posts_page ) {
if ( 'page' === get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) ) {
$posts_page = get_permalink( get_option( 'page_for_posts' ) );
} else {
$posts_page = home_url( '/' );
}
}
$posts_page = esc_url( $posts_page );
if ( 'list' === $parsed_args['style'] ) {
$output .= "<li class='cat-item-all'><a href='$posts_page'>$show_option_all</a></li>";
} else {
$output .= "<a href='$posts_page'>$show_option_all</a>";
}
}
if ( empty( $parsed_args['current_category'] ) && ( is_category() || is_tax() || is_tag() ) ) {
$current_term_object = get_queried_object();
if ( $current_term_object && $parsed_args['taxonomy'] === $current_term_object->taxonomy ) {
$parsed_args['current_category'] = get_queried_object_id();
}
}
if ( $parsed_args['hierarchical'] ) {
$depth = $parsed_args['depth'];
} else {
$depth = -1; // Flat.
}
$output .= walk_category_tree( $categories, $depth, $parsed_args );
}
if ( $parsed_args['title_li'] && 'list' === $parsed_args['style']
&& ( ! empty( $categories ) || ! $parsed_args['hide_title_if_empty'] )
) {
$output .= '</ul></li>';
}
/**
* Filters the HTML output of a taxonomy list.
*
* @since 2.1.0
*
* @param string $output HTML output.
* @param array|string $args An array or query string of taxonomy-listing arguments. See
* wp_list_categories() for information on accepted arguments.
*/
$html = apply_filters( 'wp_list_categories', $output, $args );
if ( $parsed_args['echo'] ) {
echo $html;
} else {
return $html;
}
}
Hooks
- apply_filters( ‘wp_list_categories’, string $output, array|string $args )
-
Filters the HTML output of a taxonomy list.
Skip to note 12 content
Codex
Display Categories Assigned to a Post
Display the categories (or terms from other taxonomies) assigned to a post ordered by parent-child category relationship. Similar to the function get_the_category_list() which orders the categories by name. This example must be used inside the loop.
$taxonomy = 'category'; // Get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // Separator between links. $separator = ', '; if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( array( 'title_li' => '', 'style' => 'none', 'echo' => false, 'taxonomy' => $taxonomy, 'include' => $term_ids ) ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // Display post categories. echo $terms; }Skip to note 13 content
Codex
Include or Exclude Categories
To sort categories alphabetically and include only the categories with IDs of 16, 3, 9 and 5, you could write the following code:
<ul> 'name', 'include' => array( 3, 5, 9, 16 ) ) ); ?> </ul>The following example displays category links sorted by name, shows the number of posts for each category, and excludes the category with the ID of 10 from the list.
<ul> 'name', 'show_count' => true, 'exclude' => array( 10 ) ) ); ?> </ul>Skip to note 14 content
Codex
Display or Hide the List Heading
The title_li parameter sets or hides a title or heading for the category list generated by wp_list_categories. It defaults to ‘(__(‘Categories’)’, i.e. it displays the word “Categories” as the list’s heading. If the parameter is set to a null or empty value, no heading is displayed. The following example code excludes categories with IDs 4 and 7 and hides the list heading:
<ul> array( 4,7 ), 'title_li' => '' ) ); ?> </ul>In the following example, only Categories with IDs 9, 5, and 23 are included in the list and the heading text has been changed to the word “Poetry”, with a heading style of :
<ul> array( 5, 9, 23 ), 'title_li' => '<h2>' . __( 'Poetry', 'textdomain' ) . '</h2>' ) ); ?> </ul>Skip to note 15 content
certainlyakey
Note that you can use all the arguments implemented for get_terms() function and WP_Term_Query::__construct. So, for example, the arguments
meta_keyormeta_valuecan be added and will do their job as well.Skip to note 16 content
Codex
Remove Parentheses from Category Counts
When show_count=1, each category count is surrounded by parentheses. In order to remove the parentheses without modifying core WordPress files, use the following code.
$variable = wp_list_categories( array( 'echo' => false, 'show_count' => true, 'title_li' => '<h2>' . __( 'Categories', 'textdomain' ) . '</h2>' ) ); $variable = preg_replace( '~((d+))(?=s*+<)~', '$1', $variable ); echo $variable;Skip to note 17 content
Codex
Display Terms in a custom taxonomy
With Version 3.0 the taxonomy parameter was added to enable wp_list_categories() function to list Custom Taxonomies. This example list the terms in the taxonomy genre:
// List terms in a given taxonomy using wp_list_categories (also useful as a widget if using a PHP Code plugin) $taxonomy = 'genre'; $orderby = 'name'; $show_count = false; $pad_counts = false; $hierarchical = true; $title = ''; $args = array( 'taxonomy' => $taxonomy, 'orderby' => $orderby, 'show_count' => $show_count, 'pad_counts' => $pad_counts, 'hierarchical' => $hierarchical, 'title_li' => $title ); ?> <ul> </ul>Skip to note 18 content
voichescudenis
All categories divided by comma.
strip_tags( get_the_category_list( ', ', ', ' ) )Skip to note 19 content
Codex
Only Show Children of a Category
The following example code generates category links, sorted by ID, only for the children of the category with ID 8; it shows the number of posts per category and hides category descriptions from the title attribute of the generated links. Note: If there are no posts in a parent Category, the parent Category will not display.
<ul> 'id', 'show_count' => true, 'use_desc_for_title' => false, 'child_of' => 8 ) ); ?> </ul>Skip to note 20 content
Codex
Display Categories with RSS Feed Links
The following example generates Category links sorted by name, shows the number of posts per Category, and displays links to the RSS feed for each Category.
<ul> 'name', 'show_count' => true, 'feed' => 'RSS' ) ); ?> </ul>To replace the rss link with a feed icon, you could write:
<ul> 'name', 'show_count' => true, 'feed_image' => '/images/rss.gif' ) ); ?> </ul>Skip to note 21 content
Codex
Markup and Styling of Category Lists
By default, wp_list_categories() generates nested unordered lists (ul) within a single list item (li) titled “Categories”.
You can remove the outermost item and list by setting the title_li parameter to an empty string. You’ll need to wrap the output in an ordered list (ol) or unordered list yourself (see the examples above). If you don’t want list output at all, set the style parameter to none.
You can style the output with these CSS selectors :
li.categories { ... } /* outermost list item */ li.cat-item { ... } li.cat-item-7 { ... } /* category ID #7, etc */ li.current-cat { ... } li.current-cat-parent { ... } ul.children { ... }Skip to note 22 content
nossfloda
‘include’ is missing from the parameter list.
$taxonomy = 'category'; $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); $separator = ', '; if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) { $term_ids = implode( ',', $post_terms ); $terms = wp_list_categories( array( 'title_li' => '', 'style' => 'none', 'echo' => false, 'taxonomy' => $taxonomy, 'include' => $term_ids, 'child_of' => 17, 'exclude' => 17 ) ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); echo $terms; }