返回介绍

wp_list_categories()

发布于 2017-09-11 12:21:44 字数 18043 浏览 948 评论 0 收藏 0

wp_list_categories( string|array $args = '' )

Display or retrieve the HTML list of categories.


description


参数

$args

(string|array) (Optional) Array of optional arguments.

  • 'child_of'
    (int) Term ID to retrieve child terms of. See get_terms(). Default 0.
  • 'current_category'
    (int|array) ID of category, or array of IDs of categories, that should get the 'current-cat' class. Default 0.
  • 'depth'
    (int) Category depth. Used for tab indentation. Default 0.
  • 'echo'
    (bool|int) True to echo markup, false to return it. Default 1.
  • 'exclude'
    (array|string) Array or comma/space-separated string of term IDs to exclude. If $hierarchical is true, descendants of $exclude terms will also be excluded; see $exclude_tree. See get_terms().
  • 'exclude_tree'
    (array|string) Array or comma/space-separated string of term IDs to exclude, along with their descendants. See get_terms().
  • 'feed'
    (string) Text to use for the feed link. Default 'Feed for all posts filed under [cat name]'.
  • 'feed_image'
    (string) URL of an image to use for the feed link.
  • 'feed_type'
    (string) Feed type. Used to build feed link. See get_term_feed_link(). Default empty string (default feed).
  • 'hide_empty'
    (bool|int) Whether to hide categories that don't have any posts attached to them. Default 1.
  • 'hide_title_if_empty'
    (bool) Whether to hide the $title_li element if there are no terms in the list. Default false (title will always be shown).
  • 'hierarchical'
    (bool) Whether to include terms that have non-empty descendants. See get_terms(). Default true.
  • 'order'
    (string) Which direction to order categories. Accepts 'ASC' or 'DESC'. Default 'ASC'.
  • 'orderby'
    (string) The column to use for ordering categories. Default 'ID'.
  • 'separator'
    (string) Separator between links. Default '<br />'.
  • 'show_count'
    (bool|int) Whether to show how many posts are in the category. Default 0.
  • 'show_option_all'
    (string) Text to display for showing all categories.
  • 'show_option_none'
    (string) Text to display for the 'no categories' option. Default 'No categories'.
  • 'style'
    (string) The 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'.
  • 'taxonomy'
    (string) Taxonomy name. Default 'category'.
  • 'title_li'
    (string) Text to use for the list title <li> element. Pass an empty string to disable. Default 'Categories'.
  • 'use_desc_for_title'
    (bool|int) Whether to use the category description as the title attribute. Default 1.

Default value: ''


返回值

(false|string) HTML content only if 'echo' argument is 0.


源代码

File: wp-includes/category-template.php

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'  => 1,
	);

	$r = wp_parse_args( $args, $defaults );

	if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] )
		$r['pad_counts'] = true;

	// Descendants of exclusions should be excluded too.
	if ( true == $r['hierarchical'] ) {
		$exclude_tree = array();

		if ( $r['exclude_tree'] ) {
			$exclude_tree = array_merge( $exclude_tree, wp_parse_id_list( $r['exclude_tree'] ) );
		}

		if ( $r['exclude'] ) {
			$exclude_tree = array_merge( $exclude_tree, wp_parse_id_list( $r['exclude'] ) );
		}

		$r['exclude_tree'] = $exclude_tree;
		$r['exclude'] = '';
	}

	if ( ! isset( $r['class'] ) )
		$r['class'] = ( 'category' == $r['taxonomy'] ) ? 'categories' : $r['taxonomy'];

	if ( ! taxonomy_exists( $r['taxonomy'] ) ) {
		return false;
	}

	$show_option_all = $r['show_option_all'];
	$show_option_none = $r['show_option_none'];

	$categories = get_categories( $r );

	$output = '';
	if ( $r['title_li'] && 'list' == $r['style'] && ( ! empty( $categories ) || ! $r['hide_title_if_empty'] ) ) {
		$output = '<li class="' . esc_attr( $r['class'] ) . '">' . $r['title_li'] . '<ul>';
	}
	if ( empty( $categories ) ) {
		if ( ! empty( $show_option_none ) ) {
			if ( 'list' == $r['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( $r['taxonomy'] );
			if ( ! in_array( 'post', $taxonomy_object->object_type ) && ! in_array( 'page', $taxonomy_object->object_type ) ) {
				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' == $r['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( $r['current_category'] ) && ( is_category() || is_tax() || is_tag() ) ) {
			$current_term_object = get_queried_object();
			if ( $current_term_object && $r['taxonomy'] === $current_term_object->taxonomy ) {
				$r['current_category'] = get_queried_object_id();
			}
		}

		if ( $r['hierarchical'] ) {
			$depth = $r['depth'];
		} else {
			$depth = -1; // Flat.
		}
		$output .= walk_category_tree( $categories, $depth, $r );
	}

	if ( $r['title_li'] && 'list' == $r['style'] && ( ! empty( $categories ) || ! $r['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  $args   An array of taxonomy-listing arguments.
	 */
	$html = apply_filters( 'wp_list_categories', $output, $args );

	if ( $r['echo'] ) {
		echo $html;
	} else {
		return $html;
	}
}

更新日志

Versiondescription
4.4.0Introduced the hide_title_if_empty and separator arguments. The current_category argument was modified to optionally accept an array of values.
2.1.0Introduced.

More Information

If you need a function that does not format the results, try get_categories().

Usage

By default, wp_list_categories() displays:

  • No link to all categories
  • Sorts the list of Categories by the Category name in ascending order
  • Displayed in an unordered list style
  • Does not show the post count
  • Displays only Categories with posts
  • Sets the title attribute to the Category description
  • Is not restricted to the child_of any Category
  • No feed or feed image used
  • Does not exclude any Category and includes all Categories
  • Displays the active Category with the CSS Class-Suffix ‘ current-cat’
  • Shows the Categories in hierarchical indented fashion
  • Display Category as the heading over the list
  • No SQL LIMIT is imposed (‘number’ => 0 is not shown above)
  • Displays (echos) the categories
  • No limit to depth
  • All categories.
  • The list is rendered using a new walker object of the the Walker_Category class

相关函数

Uses

  • wp-includes/category-template.php: walk_category_tree()
  • wp-includes/category-template.php: wp_list_categories
  • wp-includes/l10n.php: __()
  • wp-includes/formatting.php: esc_attr()
  • wp-includes/formatting.php: esc_url()
  • wp-includes/query.php: is_category()
  • wp-includes/query.php: is_tax()
  • wp-includes/query.php: is_tag()
  • wp-includes/query.php: get_queried_object()
  • wp-includes/query.php: get_queried_object_id()
  • wp-includes/category.php: get_categories()
  • wp-includes/functions.php: wp_parse_args()
  • wp-includes/functions.php: wp_parse_id_list()
  • wp-includes/taxonomy.php: taxonomy_exists()
  • wp-includes/taxonomy.php: get_taxonomy()
  • wp-includes/link-template.php: home_url()
  • wp-includes/link-template.php: get_post_type_archive_link()
  • wp-includes/link-template.php: get_permalink()
  • wp-includes/plugin.php: apply_filters()
  • wp-includes/option.php: get_option()
  • wp-includes/post.php: get_post_type_object()
  • Show 16 more uses Hide more uses

Used By

  • wp-includes/deprecated.php: wp_list_cats()
  • wp-includes/widgets/class-wp-widget-categories.php: WP_Widget_Categories::widget()

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 2You must log in to vote on the helpfulness of this note Contributed by 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>
    	<?php wp_list_categories( array(
    		'orderby' => '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>
    	<?php wp_list_categories( array(
    		'orderby'    => 'name',
    		'show_count' => true,
    		'exclude'    => array( 10 )
    	) ); ?> 
    </ul>
    
  2. 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;
    }
    

    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>
    	<?php wp_list_categories( array(
    		'exclude'  => 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>
    	<?php wp_list_categories( array(
    		'include'  => array( 5, 9, 23 ),
    		'title_li' => '<h2>' . __( 'Poetry', 'textdomain' ) . '</h2>'
    	) ); ?> 
    </ul>
    

    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;
    

    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>
    	<?php wp_list_categories( array(
    		'orderby'            => 'id',
    		'show_count'         => true,
    		'use_desc_for_title' => false,
    		'child_of'           => 8
    	) ); ?>
    </ul>
    

    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>
    	<?php wp_list_categories( array(
    		'orderby'    => 'name',
    		'show_count' => true,
    		'feed'       => 'RSS'
    	) ); ?>
    </ul>
    

    To replace the rss link with a feed icon, you could write:

    
    <ul>
    	<?php wp_list_categories( array(
    		'orderby'    => 'name',
    		'show_count' => true,
    		'feed_image' => '/images/rss.gif'
    	) ); ?>
    </ul>
    

    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>
    	<?php wp_list_categories( $args ); ?>
    </ul>
    

    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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文