【问题标题】:Only display Woo Commerce sub-categories based on selected Parent Category in a wordpress widget sidebar仅在 wordpress 小部件侧边栏中显示基于所选父类别的 Woo Commerce 子类别
【发布时间】:2022-04-21 08:17:14
【问题描述】:

我有一个 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>'; 
    }
}
?>

这些是我的商店外观和我想要的屏幕截图。

【问题讨论】:

    标签: php css wordpress wordpress-theming custom-wordpress-pages


    【解决方案1】:

    在主题的 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();
    }
    

    然后,转到 外观 > 小部件,将 shortcodetext 小部件抓取到您的侧边栏中并粘贴以下短代码:

    [child_category_list]
    

    Tested 在 localhost 上运行良好。

    【讨论】:

    • 完全按照答案,侧边栏中没有出现任何内容。我确实忘记提及我正在使用 WooCommerce 插件。我需要将参数传递到小部件的简码中吗?
    • 确保这个特定的侧边栏正在加载到类别页面上。您是否访问过父类别页面以查看它是否显示?
    • 我认为我的问题是我正在使用 Woo Commerce 项目类别和 Post 类别。我正在重组地图,并会在我进行更多测试时更新。
    • 所以澄清一下,我想使用 woo commerce 类别而不是帖子类别按子项和父项进行排序。
    • @curiousSloth,我认为您的代码已经在工作,而您正在询问在哪里添加该代码。无论如何,我已经更新了我的代码。这将使用简码在侧栏中显示父及其子类别。请注意,仅当当前类别存在任何子类别时才会出现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多