wp_list_categories()WP 2.1.0

Displays a list of categories as HTML links. If you click on the link, all posts from the category will be shown.

Hooks from the function

Return

null|String|false.

  • If echo=1 — HTML code.
  • If echo=0 — returns HTML code to the variable for further processing.

Usage template

$args = [
	'show_option_all'    => '',
	'show_option_none'   => __('No categories'),
	'orderby'            => 'name',
	'order'              => 'ASC',
	'style'              => 'list',
	'show_count'         => 0,
	'hide_empty'         => 1,
	'use_desc_for_title' => 1,
	'child_of'           => 0,
	'feed'               => '',
	'feed_type'          => '',
	'feed_image'         => '',
	'exclude'            => '',
	'exclude_tree'       => '',
	'include'            => '',
	'hierarchical'       => true,
	'title_li'           => __( 'Categories' ),
	'number'             => NULL,
	'echo'               => 1,
	'depth'              => 0,
	'current_category'   => 0,
	'pad_counts'         => 0,
	'taxonomy'           => 'category',
	'walker'             => 'Walker_Category',
	'hide_title_if_empty' => false,
	'separator'          => '<br />',
];

echo '<ul>';
	wp_list_categories( $args );
echo '</ul>';

Usage

<ul>
	<?php wp_list_categories( $args ); ?>
</ul>

Arguments passed to $args

$args is an array of arguments. It can be a string as well.

In addition to the following parameters, it can accept all parameters of get_terms().

child_of(int)
Show child categories. The parameter specifies the ID of the parent category (the category whose nested categories you want to show). See get_terms().
current_category(int/array)

ID of category, or array of IDs of categories, that should get the 'current-cat' class.
Category ID or array of IDs to which you need to add the class current-cat (class="current-cat").

This is necessary to highlight the category through CSS styles. Normally, this class is added to the current category on the category page. Use this option to, for example, add this class to individual pages that are not in the current category.

Since version 4.4. you can pass an array of IDS to this parameter.

depth(int)

This parameter controls the depth of nesting of the categories to be displayed. By default 0 - show all nesting levels (all child categories).

  • 0 - all nesting levels (default).
  • -1 - show all child categories, but without LI lists nesting. Cancels the option hierarchical.
  • 1 - show only first level categories (all types of nested categories will not be shown).
  • n - number - the depth of nesting you want to show. 2 - will show the categories of the first and second level.
echo(true/false/int)

Display or return for processing.

  • 1 (true) - yes, display.
  • 0 (false) - no, just return the data.

Default: 1

exclude(array/string)

Exclude categories from the list. You need to specify the ID of the categories separated by comma/space.

  • If this parameter is specified, the parameter child_of will be cancelled.
  • If the parameter heiararchical=true, the whole branch will be excluded. If heiararchical=false, then use the exclude_tree to exclude branch.

Default: ''

exclude_tree(array/string)
Exclude the category tree from the list. Specify category IDS separated by commas. The include parameter must be empty. If the parameter heirarchical=true, use exclude instead of exclude_tree.
Default: ''
include(строка)
List only the specified categories. You need to specify the ID of the categories separated by commas.
По умолчанию: ''
hide_empty(true/false/int)

Do you want to hide categories that have no posts?

  • 0 (false) - show empty (do not hide);
  • 1 (true) - do not show empty categories (hide).

Default: 1

hide_title_if_empty(true/false)
Whether to hide the $title_li element if there are no terms in the list.
Default: false (title will always be shown)
hierarchical(true/false)

Show categories as a tree. Show nested (child categories) as a nested list.

  • 1 (true) - tree view.
  • 0 (false) - show as solid type.

Default: true

order(string)

Which direction to order categories.

  • ASC - from smaller to bigger (1, 2, 3; a, b, c);
  • DESC - in reverse order, from bigger to smaller (3, 2, 1; c, b, a).

Default: 'ASC'

orderby(string)

Sort the list by specific criteria. For example, by a number of posts in each category or by category name. The following criteria are available:

  • ID - sort by ID;
  • name - sort by name (default);
  • slug - sort by slug name;
  • count - by the number of posts in the category;
  • term_group - by group.

Default: 'name'

separator(string)
Separator between links.
Default: '<br />'
show_count(true/false/int)

Whether to show how many posts are in the category. The number of posts will be shown after the category name in parentheses (for example, Psychology (16)).

  • 1 (true) - show the number of records;
  • 0 (false) - do not show the number of records.
show_option_all(string)

Text to display for showing all categories.

If you pass a non-empty string, for example, All categories, a link to all categories will be added to list (often it is a link to the blog front page). The text of the link will be the text passed to this parameter, in this case all categories.
Default: ''

show_option_none(string)
If the function does not found any categories to display, this text will be shown.
Default: 'No categories'
style(string)

The style used to display the categories list.

  • list - categories will be output as an unordered list.
  • none - categories will be output as a <a> tags separated by <br>.

Default: 'list'

taxonomy(string)
The name of the taxonomy to be processed.
Default: 'category'
title_li(string)
Text to use for the list title. If you change this parameter to '' (title_li=), the title will not be displayed at all.
Default: 'Categories'
use_desc_for_title(true/false/int)

Whether to insert the category description into the title attribute of the link (<a title="category Description" href="...):

  • 1 (true) - Yes, insert description in title, if any;
  • 0 (false) - no, do not use the description (will be: See all posts under "category name").

Default: 1

number(number)
Set the maximum number of displayed categories (SQL LIMIT). By default, no restrictions.
Default: ''
pad_counts(true/false)
Count the total number of posts in nested categories and show this number next to the parent category. Option is automatically enabled when show_counts=true and hierarchical=true.
Default: 0 (false)
feed(string)
Whether to show a link to the RSS feed (rrs-2) next to the name of the category. The text passed in this parameter will become the link text.
Default: 'Feed for all posts filed under [cat name]'
feed_image(string)
Whether to show a picture as a link to the RSS feed (rrs-2) next to the name of the category. In this parameter, you need to specify a link to the image. If this parameter is specified, the $feed parameter will be cancelled.
Default: ''
feed_type(string)
Feed type. Used to build feed link. See get_term_feed_link().
Default: '' (default feed)
walker(object)
An extension of an object (class) that is used to create a list of categories. The object passed to the parameter is an extension of the Walker_Category or Walker class.
Default: 'Walker_Category'

Examples

0

#1 Sort alphabetically

You can use the following code, to sort categories alphabetically (orderby=name) and to include in the list only the category with ID equal to 16,3,9,5 (include=16,3,9,5):

<ul>
	<?php wp_list_categories('orderby=name&include=3,5,9,16'); ?>
</ul>
0

#2 Sort by name

The following example sorts the categories by name (orderby=name), shows the number of posts in each category (show_count=1), and excludes the category with ID 10 (exclude=10) from the list:

<ul>
	<?php wp_list_categories('orderby=name&show_count=1&exclude=10'); ?>
</ul>
0

#3 Remove the category list header

By resetting the title_li parameter. By default, this parameter is __('Categories'), if you set it to null or '', the title of the list will not be shown at all.

The following example excludes categories 4 and 7, and removes the category list header:

<ul>
	<?php wp_list_categories('exclude=4,7&title_li='); ?>
</ul>
0

#4 Print only the specified categories

This example will show only a list of categories with ID 9, 5 and 23, and will change the title of the list to "Poetry", which will be enclosed in the tags <h2>:

<ul>
	<?php wp_list_categories('include=5,9,23&title_li=<h2>' . __('Poetry') . '</h2>' ); ?>
</ul>
0

#5 Output only child categories

Use the following code to display only categories nested in category 8 (child_of=8) and sort them by ID (orderby=id)/ Also show the number of posts in each category (show_count=1) and remove the category description from the title attribute (use_desc_for_title=0):

<ul>
	  <?php wp_list_categories('orderby=id&show_count=1&use_desc_for_title=0&child_of=8'); ?>
</ul>
0

#6 Remove the brackets around the number of posts in each category

To do this, we get a list of categories in the variable (echo=0) and pass it through the php function str_replace(), which removes the brackets:

<?php
$cats = wp_list_categories('echo=0&show_count=1&title_li=<h2>Категории</h2>');
$cats = str_replace( ['(',')'], '', $cats );
echo $cats;
?>
0

#7 Show a list of categories with a link to the RSS-feed

To do this, use the parameter feed=RSS, as in this example, the list will be sorted by category name (orderby=name) and each category will show the number of posts (show_count=1):

<ul>
   <?php wp_list_categories('orderby=name&show_count=1&feed=RSS'); ?>
</ul>
0

#8 If you want to show a link to a picture instead of text links to RSS feed, then use the parameter feed_image:

<ul>
   <?php wp_list_categories('orderby=name&show_count=1&feed_image=/images/rss.gif'); ?>
</ul>
0

#9 Display a list of custom (user-defined) taxonomy

In version 3.0 it became possible to list custom taxonomies using the taxonomy parameter. The example below shows how to pass parameters in an array, not in a string:

<?php
// List of categories of custom taxonomy genre

$args = array(
  'taxonomy'     => 'genre', // Name of the taxonomy
  'orderby'      => 'name',  // Sorting by name
  'show_count'   => 0,       // Don't show the number of posts
  'pad_counts'   => 0,       // Don't show the parent's number of posts
  'hierarchical' => 1,       // Tree view
  'title_li'     => ''       // Without title
);
?>

<ul>
<?php wp_list_categories( $args ); ?>
</ul>
0

#10 CSS classes for styling <li> list

CSS Classes are created automatically by the wp_list_categories() function. The main HTML tag (ul) is set arbitrarily, so you can set your own css class there. And for li tag the following css classes are used:

li.categories { ... }  /* common selector */
li.cat-item { ... }
li.cat-item-7 { ... }  /* Category with ID 7 */
li.current-cat { ... }
li.current-cat-parent { ... }
ul.children { ... }

Changelog

Since 2.1.0 Introduced.
Since 4.4.0 Introduced the hide_title_if_empty and separator arguments.
Since 4.4.0 The current_category argument was modified to optionally accept an array of values.
Since 6.1.0 Default value of the 'use_desc_for_title' argument was changed from 1 to 0.

wp_list_categories() code WP 6.5.2

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;
	}
}