$conf, $runtime; function_exists('chdir') AND chdir(APP_PATH); $r = 'mysql' == $conf['cache']['type'] ? website_set('runtime', $runtime) : cache_set('runtime', $runtime); } function runtime_truncate() { global $conf; 'mysql' == $conf['cache']['type'] ? website_set('runtime', '') : cache_delete('runtime'); } register_shutdown_function('runtime_save'); ?>loop - Showing categories and subcategories with posts|Programmer puzzle solving
最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

loop - Showing categories and subcategories with posts

matteradmin10PV0评论

Basically as the title says I want to get list of categories and subcategories and then posts(with links to them) for those categories/subcategories.

This is the structure I'm trying to achieve:

  • Category 1
    • Subcategory 1 within category 1
      • Post 1 within subcategory 1
      • Post 2 within subcategory 1
      • Post 3 within subcategory 1
    • Subcategory 2 within category 1
      • Post 1 within subcategory 2
      • Post 2 within subcategory 2
      • Post 3 within subcategory 2
    • Subcategory 3 within category 1
      • Post 1 within subcategory 3
      • Post 2 within subcategory 3
      • Post 3 within subcategory 3
    • Posts that have no subcategory
      • Post 1 with no subcategory
      • Post 1 with no subcategory
  • Category 2
    • Subcategory 1 within category 2
      • Post 1 within subcategory 1
      • Post 2 within subcategory 1
      • Post 3 within subcategory 1
    • Subcategory 2 within category 2
      • Post 1 within subcategory 2
      • Post 2 within subcategory 2
      • Post 3 within subcategory 2
    • Subcategory 3 within category 2
      • Post 1 within subcategory 2
      • Post 2 within subcategory 2
      • Post 3 within subcategory 2
    • Posts that have no subcategory
      • Post 1 with no subcategory
      • Post 1 with no subcategory

Now so far after after reading everything I could found on the subject I have the following code:

<ul>   
    <?php 
        $get_parent_cats = array(
            'parent' => '0' //get top level categories only
        ); 

        $all_categories = get_categories( $get_parent_cats );//get parent categories 

        foreach( $all_categories as $single_category ){
            //for each category, get the ID
            $catID = $single_category->cat_ID;

            echo '<li><a href=" ' . get_category_link( $catID ) . ' ">' . $single_category->name . '</a>'; //category name & link
            $get_children_cats = array(
                'child_of' => $catID //get children of this parent using the catID variable from earlier
            );

            $child_cats = get_categories( $get_children_cats );//get children of parent category
            echo '<ul class="children">';
                foreach( $child_cats as $child_cat ){
                    //for each child category, get the ID
                    $childID = $child_cat->cat_ID;

                    //for each child category, give us the link and name
                    echo '<a href=" ' . get_category_link( $childID ) . ' ">' . $child_cat->name . '</a>';

                }
            echo '</ul></li>';
        } //end of categories logic ?>
</ul>

Now this code shows categories and subcategories well but I need to somehow loop through my posts and show them withing categories/subcategories. I have also tried to use fallowing code:

    <?php
        // get all the categories from the database
        $cats = get_categories(); 

            // loop through the categries
            foreach ($cats as $cat) {
                // setup the cateogory ID
                $cat_id= $cat->term_id;
                // Make a header for the cateogry
                echo "<h2>".$cat->name."</h2>";
                // create a custom wordpress query
                query_posts("cat=$cat_id&posts_per_page=100");
                // start the wordpress loop!
                if (have_posts()) : while (have_posts()) : the_post(); ?>

                    <?php // create our link now that the post is setup ?>
                    <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
                    <?php echo '<hr/>'; ?>

                <?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
            <?php } // done the foreach statement ?>

        </div><!-- #content -->
    </div><!-- #container -->

This code shows all categories and posts within particular category, but the structure is not the one I want. I have been trying to combine these two snippets of code for two days, but nothing I try gives me the result I want. I am inexperienced with Wordpress and I could really use help with this.

Basically as the title says I want to get list of categories and subcategories and then posts(with links to them) for those categories/subcategories.

This is the structure I'm trying to achieve:

  • Category 1
    • Subcategory 1 within category 1
      • Post 1 within subcategory 1
      • Post 2 within subcategory 1
      • Post 3 within subcategory 1
    • Subcategory 2 within category 1
      • Post 1 within subcategory 2
      • Post 2 within subcategory 2
      • Post 3 within subcategory 2
    • Subcategory 3 within category 1
      • Post 1 within subcategory 3
      • Post 2 within subcategory 3
      • Post 3 within subcategory 3
    • Posts that have no subcategory
      • Post 1 with no subcategory
      • Post 1 with no subcategory
  • Category 2
    • Subcategory 1 within category 2
      • Post 1 within subcategory 1
      • Post 2 within subcategory 1
      • Post 3 within subcategory 1
    • Subcategory 2 within category 2
      • Post 1 within subcategory 2
      • Post 2 within subcategory 2
      • Post 3 within subcategory 2
    • Subcategory 3 within category 2
      • Post 1 within subcategory 2
      • Post 2 within subcategory 2
      • Post 3 within subcategory 2
    • Posts that have no subcategory
      • Post 1 with no subcategory
      • Post 1 with no subcategory

Now so far after after reading everything I could found on the subject I have the following code:

<ul>   
    <?php 
        $get_parent_cats = array(
            'parent' => '0' //get top level categories only
        ); 

        $all_categories = get_categories( $get_parent_cats );//get parent categories 

        foreach( $all_categories as $single_category ){
            //for each category, get the ID
            $catID = $single_category->cat_ID;

            echo '<li><a href=" ' . get_category_link( $catID ) . ' ">' . $single_category->name . '</a>'; //category name & link
            $get_children_cats = array(
                'child_of' => $catID //get children of this parent using the catID variable from earlier
            );

            $child_cats = get_categories( $get_children_cats );//get children of parent category
            echo '<ul class="children">';
                foreach( $child_cats as $child_cat ){
                    //for each child category, get the ID
                    $childID = $child_cat->cat_ID;

                    //for each child category, give us the link and name
                    echo '<a href=" ' . get_category_link( $childID ) . ' ">' . $child_cat->name . '</a>';

                }
            echo '</ul></li>';
        } //end of categories logic ?>
</ul>

Now this code shows categories and subcategories well but I need to somehow loop through my posts and show them withing categories/subcategories. I have also tried to use fallowing code:

    <?php
        // get all the categories from the database
        $cats = get_categories(); 

            // loop through the categries
            foreach ($cats as $cat) {
                // setup the cateogory ID
                $cat_id= $cat->term_id;
                // Make a header for the cateogry
                echo "<h2>".$cat->name."</h2>";
                // create a custom wordpress query
                query_posts("cat=$cat_id&posts_per_page=100");
                // start the wordpress loop!
                if (have_posts()) : while (have_posts()) : the_post(); ?>

                    <?php // create our link now that the post is setup ?>
                    <a href="<?php the_permalink();?>"><?php the_title(); ?></a>
                    <?php echo '<hr/>'; ?>

                <?php endwhile; endif; // done our wordpress loop. Will start again for each category ?>
            <?php } // done the foreach statement ?>

        </div><!-- #content -->
    </div><!-- #container -->

This code shows all categories and posts within particular category, but the structure is not the one I want. I have been trying to combine these two snippets of code for two days, but nothing I try gives me the result I want. I am inexperienced with Wordpress and I could really use help with this.

Share Improve this question asked Jun 15, 2017 at 0:57 KaradjordjeKaradjordje 1912 gold badges2 silver badges8 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 1

Update: Complete code

<ul>   
        <?php 
            $get_parent_cats = array(
                'parent' => '0' //get top level categories only
            ); 

            $all_categories = get_categories( $get_parent_cats );//get parent categories 

            foreach( $all_categories as $single_category ){
                //for each category, get the ID
                $catID = $single_category->cat_ID;

                echo '<li><a href=" ' . get_category_link( $catID ) . ' ">' . $single_category->name . '</a>'; //category name & link
                 echo '<ul class="post-title">';

                $query = new WP_Query( array( 'cat'=> $catID, 'posts_per_page'=>10 ) );
                while( $query->have_posts() ):$query->the_post();
                 echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
                endwhile;
                wp_reset_postdata();

                echo '</ul>';
                $get_children_cats = array(
                    'child_of' => $catID //get children of this parent using the catID variable from earlier
                );

                $child_cats = get_categories( $get_children_cats );//get children of parent category
                echo '<ul class="children">';
                    foreach( $child_cats as $child_cat ){
                        //for each child category, get the ID
                        $childID = $child_cat->cat_ID;

                        //for each child category, give us the link and name
                        echo '<a href=" ' . get_category_link( $childID ) . ' ">' . $child_cat->name . '</a>';

                         echo '<ul class="post-title">';

                        $query = new WP_Query( array( 'cat'=> $childID, 'posts_per_page'=>10 ) );
                        while( $query->have_posts() ):$query->the_post();
                         echo '<li><a href="'.get_the_permalink().'">'.get_the_title().'</a></li>';
                        endwhile;
                        wp_reset_postdata();

                        echo '</ul>';

                    }
                echo '</ul></li>';
            } //end of categories logic ?>
    </ul>

This function works right away, just make sure to change the names to your own taxonomy and post type. Feel free to read the comments for more clarification.

function ow_categories_with_subcategories_and_posts( $taxonomy, $post_type ) {
    $taxonomy   = $taxonomy;
    $post_type  = $post_type;

    // Get the top categories that belong to the provided taxonomy (the ones without parent)
    $categories = get_terms( 
        array(
            'taxonomy'   => $taxonomy,
            'parent'     => 0, // <-- No Parent
            'orderby'    => 'term_id',
            'hide_empty' => true // <-- change to false to also display empty ones
        )
    );
    ?>
    <div>
        <?php
        // Iterate through all categories to display each individual category
        foreach ( $categories as $category ) {

            $cat_name = $category->name;
            $cat_id   = $category->term_id;
            $cat_slug = $category->slug;

            // Display the name of each individual category
            echo '<h3>Category: ' . $cat_name . ' - ID: ' . $cat_id . ' - Slug: ' . $cat_slug  . '</h3>'; 


            // Get all the subcategories that belong to the current category
            $subcategories = get_terms(
                array(
                    'taxonomy'   => $taxonomy,
                    'parent'     => $cat_id, // <-- The parent is the current category
                    'orderby'    => 'term_id',
                    'hide_empty' => true
                )
            );
            ?>
            <div>
                <?php
                // Iterate through all subcategories to display each individual subcategory
                foreach ( $subcategories as $subcategory ) {

                    $subcat_name = $subcategory->name;
                    $subcat_id   = $subcategory->term_id;
                    $subcat_slug = $subcategory->slug;

                    // Display the name of each individual subcategory with ID and Slug
                    echo '<h4>Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug  . '</h4>';

                    // Get all posts that belong to this specific subcategory
                    $posts = new WP_Query(
                        array(
                            'post_type'      => $post_type,
                            'posts_per_page' => -1, // <-- Show all posts
                            'hide_empty'     => true,
                            'order'          => 'ASC',
                            'tax_query'      => array(
                                array(
                                    'taxonomy' => $taxonomy,
                                    'terms'    => $subcat_id,
                                    'field'    => 'id'
                                )
                            )
                        )
                    );

                    // If there are posts available within this subcategory
                    if ( $posts->have_posts() ):
                        ?>
                        <div>
                            <?php

                            // As long as there are posts to show
                            while ( $posts->have_posts() ): $posts->the_post();

                                //Show the title of each post with the Post ID
                                ?>
                                <p>Post: <?php the_title(); ?> - ID: <?php the_ID(); ?></p>
                                <?php

                            endwhile;
                            ?>
                        </div>
                        <?php
                    else:
                        echo 'No posts found';
                    endif;

                    wp_reset_query();
                }
                ?>
            </div>
            <?php
        }
        ?>
    </div>
    <?php
}
ow_categories_with_subcategories_and_posts( 'the_name_of_your_taxonomy', 'the_name_of_your_post_type' );
Post a comment

comment list (0)

  1. No comments so far