[英]Only display Woo Commerce sub-categories based on selected Parent Category in a wordpress widget sidebar
我有一个 WordPress 侧边栏,我只想显示父类别的子项。 我的结构如下
所有产品 > 父类 > 子类
如何让侧边栏仅显示父类别和子类别。
我阅读了实现此代码的解决方案,但不确定将其放在文件中的哪个位置。
<?php
if (is_category()) {
$cat = get_query_var('cat');
$this_category = get_category($cat);
$this_category = wp_list_categories('hide_empty=0&hierarchical=true&orderby=id&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
if($this_category !='<li>No categories</li>')
{
echo '<h3>Products</h3>';
echo '<ul>'.$this_category.'</ul>';
}
}
?>
这些是我的商店外观和我想要的屏幕截图。
在主题的functions.php文件中创建一个简码,如下所示:
add_shortcode('child_category_list', 'get_child_category_list');
function get_child_category_list(){
ob_start();
// Only on product parent category pages
if( is_product_category() ) {
$parent = get_queried_object();
$categories = get_term_children( $parent->term_id, 'product_cat' );
if ( $categories && ! is_wp_error( $categories ) ) :
echo '<ul>';
echo '<li>';
echo '<a href="'.get_term_link ($parent->term_id, 'product_cat').'">'.$parent->name.'</a>';
echo '<ul>';
foreach($categories as $category) :
$term = get_term( $category, 'product_cat' );
echo '<li>';
echo '<a href="'.get_term_link($term).'" >';
echo $term->name;
echo '</a>';
echo '</li>';
endforeach;
echo '</ul>';
echo '<li>';
echo '</ul>';
endif;
}
return ob_get_clean();
}
然后, go 到Appearance > Widgets ,将短代码或文本小部件抓取到您的侧边栏中并粘贴以下短代码:
[child_category_list]
在 localhost 上测试过并且工作正常。
@atiquratik
以下可能吗? 如果单击没有其他子类别的子类别页面而不是显示没有其他子类别的内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.