[英]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.