自定义 wp_list_categories 函数 html 输出
网站顶端的标签归档页是很久之前参照网友的文章弄的,后来为了和谐又加了个分类归档页。这个页面调用的关键函数是 wp_list_categories(),相关的说明可以参见 wp_list_categories() | Function | WordPress Developer Resources。

分类归档页是上图这样的,后面括号中的数字表示该分类下的文章数。一直以来看着都有点别扭,想把它改成“生活感悟(188 篇文章)”这种样式,只是之前不知道怎么弄。这两天稍微了解了下 WordPress 过滤器的用法,正好看到 wp_list_categories() 函数的代码中自建了跟函数同名的过滤器:
$html = apply_filters( 'wp_list_categories', $output, $args );于是在主题 functions.php 里找了段相似代码,照葫芦画瓢的写了下面这段:
function customize_wp_list_categories( $output, $args ) {
	$pattern = '/<\/a>\s\((\d+)\)\s/i';
	$replacement = '($1 篇文章)';
	$output = preg_replace( $pattern, $replacement, $output );
	return $output;
}
add_filter( 'wp_list_categories', 'customize_wp_list_categories', 10, 2 );最后的效果就是这样的:

另外 wp_list_categories() 函数输出分类,我设置为按照 ID 的顺序 'orderby' => 'id',却发现跟网页上面的导航栏顺序不一致。后台看了下才发现分类的 ID 并不是按照我预想的顺序排列的,这应该跟起初建站时创建分类出错又删除或者重命名等有关。所以网上找了下如何修改分类目录 ID,这里只记录使用 SQL 语句的方法。
update wp_terms              set term_id          = 4 where term_id          = 21;
update wp_term_taxonomy      set term_id          = 4 where term_id          = 21;
update wp_term_taxonomy      set parent           = 4 where parent           = 21;
update wp_term_taxonomy      set term_taxonomy_id = 4 where term_taxonomy_id = 21;
update wp_term_relationships set term_taxonomy_id = 4 where term_taxonomy_id = 21;如上所示。其中 21 为目前的 ID,4 为想要修改为的 ID。
@沉沦 毕竟这也是我的一大爱好啊,虽然属于外行..
 毕竟这也是我的一大爱好啊,虽然属于外行..
大。。。。大佬!
@姜辰 ..你这貌似是漫画里常用的表达方式,哈哈!
@sys 是不是满脸大汗?一脸惊讶?
@姜辰 还有眉头紧皱,瞳孔骤缩~
改ID干啥,不是有个orderby参数吗
@大致 orderby 达不成我想要的次序,否则也不必找这个麻烦了。另外说到底对 ID 是有点强迫症,这没法治