简体   繁体   中英

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. 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:

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:

[child_category_list]

Tested on localhost & its working fine.

@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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM