Show subcategories and posts from parent category

So I have this problem regarding a loop in wordpress.
I have the following structure on my site:

  • Parent category 1
    • Children's category 1
    • Children's category 2
  • Parent category 2
    • Children's category 1
    • Children's category 2
      • Post Cat2.1
      • Post Cat2.2
    • Message 1
    • Message 2

In this case, "Parent Category 2" has a category of children and positions. What I need to display on the Parent Category page are the child categories and their positions without the child category headings.
I have searched everywhere but it looks like I was looking for a bug, any help would be much appreciated.

+3


source to share


1 answer


I think this might help:

$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() ) ...
    }
 }
}

      



also he posted Here

hope this can help you :)

0


source







All Articles