【问题标题】:wp_list_categories() - display first level categories and only current term's children in subcategory pagewp_list_categories() - 在子类别页面中显示第一级类别和当前术语的子项
【发布时间】:2018-04-16 07:31:42
【问题描述】:

我正在使用 WordPress。

有多个类别及其子类别。在一般页面中,我显示所有第一级类别。这是我的代码:

$args = array(
   'type' => 'product-items',
   'child_of'  => 0,
   'parent'  => '',
   'order' => 'DESC',
   'hide_empty' => 0,
   'hierarchical' => 1,
   'exclude' => '',
   'include' => '',
   'number' => '',
   'taxonomy' => 'product-category',
   'pad_counts' => false,
   'depth' => 1,
   'title_li' => '' 
);
wp_list_categories($args);

单击并进入第一级类别后,您只需在那里查看其子类别。当我删除 'depth' => 1, 选项时,所有子项都出现在其父类别下,但对于页面速度/加载,在子页面中我需要显示所有第一级类别,但只显示当前类别的子项。

例如,我有以下 3 个类别:

  • 1 类
  • 2 类
  • 第 3 类

假设我点击了“类别 1”。现在是这样的:

  • 类别 1
    • 1 的第一个子类别
    • 1 的第二个子类别
    • 1 的第三个子类别
  • 类别 2
    • 第 2 个子类别
      • 第二类子的第一子
      • 第二类子的第二子
      • 第二类子的第三个子
    • 2 的第二个子类别
    • 2 的第三个子类别
  • 类别 3
    • 第 3 个子类别
    • 3 的第二个子类别
    • 3 的第三个子类别

但我需要它在子页面中是这样的:

  • 类别 1
    • 1 的第一个子类别
    • 1 的第二个子类别
    • 1 的第三个子类别
  • 2 类
  • 第 3 类

不确定如何使用wp_list_categories() 函数实现此目的。请问有什么想法吗?

【问题讨论】:

    标签: php wordpress categories custom-taxonomy taxonomy-terms


    【解决方案1】:

    我会选择get_terms() 路径。 比如

    $terms = get_terms($args);
    
    foreach($terms as $term){
       // If $term is current term use get_terms() again to fetch its children
    }
    

    https://developer.wordpress.org/reference/functions/get_terms/

    【讨论】:

      【解决方案2】:

      如果你使用 2 get_terms() 而不是 wp_list_categories 会更好。它会更快且可定制。一个用于父类别,另一个用于当前类别的子类别。这是工作示例:

         function display_cats($cats,$current=0,$current_children=array()){
          $ret= '<ul>';
          foreach ($cats as $cs){
            $children=($current!=$cs->term_id)?'':display_cats($current_children);
            $ret.= '<li> <a href="'.get_term_link($cs->term_id).'"> '.$cs->name.'</a> '.$children.' </li>
            ';
          }
          $ret.= '</ul>';
          return $ret;
        }
      
      
        $current_cat=9;//for example
        $parents=get_terms('product_cat',array('taxonomy'=>'product_cat','echo'=>false,'depth'=>0));
        $current_children=get_terms('product_cat',array('taxonomy'=>'product_cat','child_of'=>  $current_cat ,'echo'=>false));
        echo display_cats($parents,$current_cat,$current_children);
      

      【讨论】:

        【解决方案3】:

        对于仍然需要帮助的任何人,这里是如何做到的。

        $category = get_queried_object();
        $category_id = $category->term_id;
        

        从中我们将获得当前的类别 id,我们需要将其传递给数组。

        'child_of'  => $category_id,
        

        这将为您提供当前类别的所有子类别。

        希望这有帮助。

        【讨论】:

          猜你喜欢
          • 2015-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-11-25
          • 1970-01-01
          • 1970-01-01
          • 2020-01-06
          • 2021-09-03
          相关资源
          最近更新 更多