在我们开发WordPress主题的过程中,如果有一个需求是要获取到父分类的所有子分类,该怎么实现呢?
其实这个需求是很简单的,几行代码就可以搞定。

今天路途吧给大家带来一个小小的wordpress教程,如何在父分类获取所有子分类/二级分类。

首先在function.php里面添加下面的代码。

//父分类获取所有子分类 
function get_category_root_id($cat) {  
	$this_category = get_category($cat); // 取得当前分类  
	while($this_category->category_parent) // 若当前分类有上级分类时,循环  
	{  
		$this_category = get_category($this_category->category_parent); // 将当前分类设为上级分类往上爬  
	}  
	return $this_category->term_id; // 返回根分类的id号  
}

使用方法

将下面代码放在需要用到子分类的父分类即可

<?php wp_list_categories( 
	$args = array(
		\\\\\\\'show_option_all\\\\\\\'    => \\\\\\\'\\\\\\\',
		\\\\\\\'orderby\\\\\\\'            => \\\\\\\'name\\\\\\\',
		\\\\\\\'use_desc_for_title\\\\\\\' => 1,
		\\\\\\\'child_of\\\\\\\'           => get_category_root_id($cat),
		\\\\\\\'optioncount\\\\\\\'=>1,
		\\\\\\\'hierarchical\\\\\\\'       => 1,
		\\\\\\\'title_li\\\\\\\'           => \\\\\\\'\\\\\\\',
		\\\\\\\'show_option_none\\\\\\\'   => __(\\\\\\\'<span style=\\\\\\\"padding:0 20px;\\\\\\\">抱歉,暂无分类。</span>\\\\\\\'),
		\\\\\\\'depth\\\\\\\'              => 1,
		\\\\\\\'taxonomy\\\\\\\'           => \\\\\\\'category\\\\\\\',
		\\\\\\\'walker\\\\\\\'             => null
	)); 
?>

 

本站声明:
1. 本站所有资源来源于网络,分享目的仅供大家学习和交流! 2. 不得使用于非法商业用途,不得违反国家法律。否则后果自负! 3. 本站提供的资源,都不包含技术服务请大家谅解! 4. 如有链接无法下载、失效或广告,请联系站长处理!

再次声明:如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。