[英]Only display Woo Commerce sub-categories based on selected Parent Category in a wordpress widget sidebar
I have a WordPress sidebar that I want to only display the children of the parent category.我有一个 WordPress 侧边栏,我只想显示父类别的子项。 My structure is as follows
我的结构如下
All Products > Parent Category > Children Categories所有产品 > 父类 > 子类
How do I get the sidebar to only display the Parent Category and Children Categories.如何让侧边栏仅显示父类别和子类别。
I read a solution to implement this code but I'm not sure where to put it inside the files.我阅读了实现此代码的解决方案,但不确定将其放在文件中的哪个位置。
<?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>';
}
}
?>
These are screenshots from what my shop looks like and what I want.这些是我的商店外观和我想要的屏幕截图。
Create a shortcode in your theme's functions.php file as follows:在主题的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();
}
Then, go to Appearance > Widgets , grab either shortcode or text widget into your sidebar and paste following shortecode:然后, go 到Appearance > Widgets ,将短代码或文本小部件抓取到您的侧边栏中并粘贴以下短代码:
[child_category_list]
Tested on localhost & its working fine.在 localhost 上测试过并且工作正常。
@atiquratik @atiquratik
Would the following be possible?以下可能吗? If clicking on a sub-category page with no further child categories instead of showing nothing showing the other child-categories?
如果单击没有其他子类别的子类别页面而不是显示没有其他子类别的内容?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.