wp_list_categories函数概述
在WordPress体系中,wp_list_categories函数承担着罗列系统内所有分类的任务。该函数提供了大量参数以精确控制输出样式,鉴于有朋友近期咨询此功能,特此整理相关使用要点。
由于WordPress内置了扩展小工具功能,用户无需编写额外代码即可在侧边栏或任意指定位置直接展示分类列表。正因如此,wp_list_categories函数的实际使用频率相对较低。不过,其操作逻辑与wp_list_bookmarks函数颇为相似,便于熟悉后者者上手。
wp_list_categories函数的主要作用是生成并展示系统中的分类链接。关于该函数的详细英文说明文档,有兴趣的读者可自行查阅官方资料获取更多信息。
具体用法
<?php
wp_list_categories( $args );
$args = array(
'show_option_all' => '',//是否列出分类链接
'orderby' => 'name',//按名称排列
'order' => 'ASC',//升、降序
'style' => 'list',//是否用列表(ul>li)
'show_count' => 0,//是否显示文章数量
'hide_empty' => 1,//是否显示无日志分类
'use_desc_for_title' => 1,//是否显示分类描述
'child_of' => 0,//是否限制子分类
'feed' => '',//是否显示rss
'feed_type' => '',//rss类型
'feed_image' => '',//是否显示rss图片
'exclude' => '',//排除分类的ID,多个用',(英文逗号)'分隔
'exclude_tree' => '',//排除分类树,即父分类及其下的子分类
'include' => '',//包括的分类
'hierarchical' => true,//是否将子、父分类分级
'title_li' => __( 'Categories' ),//列表标题的名称
'show_option_none' => __('No categories'),//无分类时显示的标题
'number' => null,//显示分类的数量
'echo' => 1,//是否显示,显示或者返回字符串
'depth' => 0,//层级限制
'current_category' => 0,//添加一个没有的分类
'pad_counts' => 0,//这个我也不明白
'taxonomy' => 'category',//使用的分类法
'walker' => null//用于显示的类(很复杂的概念)
?>
对于'pad_counts'这一参数,其具体作用机制尚需进一步探究。若对此感兴趣,建议深入研究官方文档中的解释,或者参考wp_list_bookmarks的相关用法进行对比理解。
pad_counts
(boolean) Calculates link or post counts by including items from child categories. If show_counts and hierarchical are true this is automatically set to true. This parameter added at Version 2.9 Valid values:
1 (true)
0 (false) – default
以下是一个使用实例:需要显示ID分别为3、5、9和16的分类链接,并要求结果按照分类名称进行排序。
<?php wp_list_categories('orderby=name&include=3,5,9,16'); ?>
另一个示例:创建一个以“Poetry”为标题的分类列表,其中包含ID为5、9和23的分类项。
<?php wp_list_categories('include=5,9,23&title_li=<h2>' . __('Poetry') . '</h2>' ); ?>
当然,参数的传递方式也可以更加灵活,例如将各项参数整合为一个数组形式进行书写,这样代码结构会更加清晰。
<?php
$taxonomy = 'genre';
$orderby = 'name';
$show_count = 0; // 1 for yes, 0 for no
$pad_counts = 0; // 1 for yes, 0 for no
$hierarchical = 1; // 1 for yes, 0 for no
$title = '';
$args = array(
'taxonomy' => $taxonomy,
'orderby' => $orderby,
'show_count' => $show_count,
'pad_counts' => $pad_counts,
'hierarchical' => $hierarchical,
'title_li' => $title
);
?>
<?php wp_list_categories( $args ); ?>
此外,需注意taxonomy(分类法)的概念,它是相对于标签(tag)而言的一个独立体系,在调用时需明确区分。