我的wordpress上有这个类别:
Test1
- Sub1OfTest1
- Sub2OfTest1
Test2
- Sub1OfTest2
- Sub2OfTest2
现在我在网址:http://localhost/wordpress/category/test1
我在文件category-test1.php
<?php
$categories = get_categories('child_of=2');
print_r($categories);
foreach ($categories as $category) : ?>
<div class="qitem">
<a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>">
<?php echo $category->name; ?>
</a>
<h4>
<span class="caption">
<?php echo $category->name; ?>
</span>
</h4>
<p>
<span class="caption">
<?php echo $category->description; ?>
</span>
</p>
</div>
<?php
endforeach;
?>
我正在尝试显示Test1的子类别,但代码只返回array()。我错过了什么?
答案 0 :(得分:10)
该类别是空的吗?默认情况下,WordPress会隐藏emptr类别。尝试:
$categories = get_categories('child_of=2&hide_empty=0');
编辑:已修复,谢谢@Stoep
答案 1 :(得分:0)
child_of
的{{1}}参数按其ID指定类别 - 假设您按顺序创建了类别,代码get_categories
可能正在请求Sub1OfTest1的子类别。
要获取类别的ID,请转到帖子→类别,然后单击类别。 cat_ID将位于页面的URL中。
答案 2 :(得分:0)
尝试这一点 - Show wordpress subcategories only
该主题也可能有所帮助,因为有不同的解决方案可以显示子类别。
答案 3 :(得分:0)
//这是获取子类别和子子类别的编码
$args = array
(
'number' => $number,
'orderby' => 'title',
'order' => 'ASC',
'hide_empty' => false,
'include' => array(11,281,28,51,99,93,33,55,107,20),
'exclude' => array(32,29),
);
$product_categories = get_terms( 'product_cat', $args );
// echo '<pre>';
// print_r($product_categories);
// echo '</pre>';
foreach($product_categories as $data):
if($data->slug = 'cooking')
{
$child_arg = array('hide_empty'=>false,'parent'=>$data->term_id,'exclude'=>array(32,29));
}
else
{
$child_arg = array('hide_empty'=>false,'parent'=>$data->term_id);
}
$child_terms = get_terms('product_cat',$child_arg);
// echo "<pre>";
// print_r($child_terms);
// echo "</pre>";
foreach($child_terms as $data1):
if($data1->slug = 'cooking')
{
$sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id,'exclude'=>array(32,29));
}
else
{
$sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id);
}
$sub_child_terms = get_terms('product_cat',$sub_child_arg);
// echo "<pre>";
// print_r($sub_child_terms);
// echo "</pre>";
endforeach;
endforeach;
?>