【问题标题】:Display Subcategories and post from a Parent Category显示子类别和来自父类别的帖子
【发布时间】:2013-01-24 21:19:50
【问题描述】:

所以我对 wordpress 中的循环有这个问题。
我的网站中有以下结构:

  • 父类别 1
    • 儿童类别 1
    • 儿童 2 类
  • 父类别 2
    • 儿童类别 1
    • 儿童 2 类
      • 发布 Cat2.1
      • 发布 Cat2.2
    • 发布 1
    • 发布 2

在这种情况下,“父类别 2”具有子类别和帖子。我需要在“父类别页面”中显示的是子类别及其不带子类别帖子的帖子。
我到处找,但似乎我一直在寻找错误,任何帮助将不胜感激

【问题讨论】:

    标签: wordpress loops categories posts


    【解决方案1】:

    我认为这会有所帮助:

    $cat_id = get_query_var('cat');
    
    if( ! empty( $cat_id ) ) {
    $category = get_category( $cat_id, ARRAY_A );
    
    if( ! empty( $category ) ) {
        // parent category
        if( $category['parent'] === '0' ) {
    
            // get child IDs
            $terms = get_term_children( $cat_id, 'category' );
    
            foreach( $terms as $term_id ) {
                $child_category = get_term( $term_id, 'category' );
    
                // if you need the category
                $category_name = $child_category->name;
    
    
                /**
                 * Sample data in your child category object: 
                 * 
                 * object(stdClass)[365]
                          public 'term_id' => string '14' (length=2)
                          public 'name' => string 'Child 1' (length=7)
                          public 'slug' => string 'child-1' (length=7)
                          public 'term_group' => string '0' (length=1)
                          public 'term_taxonomy_id' => string '14' (length=2)
                          public 'taxonomy' => string 'category' (length=8)
                          public 'description' => string '' (length=0)
                          public 'parent' => string '12' (length=2)
                          public 'count' => string '5' (length=1)
                          public 'object_id' => string '33' (length=2)
                 * 
                 * 
                 */
    
                // do whatever you like with the categories now...
            }
    
        } else { // in child category
            // do the regular loop here, if ( have_posts() ) ...
        }
     }
    }
    

    也发布了Here

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      相关资源
      最近更新 更多