admin管理员组

文章数量:1305728

I know I can use wp_list_categories() to list categories, but how can I achieve to list also the posts under the respective categories, below an example what I want to achieve:

  • category1
  • -- post under cat1
  • -- post under cat1
  • -- post under cat1
  • category2
  • -- post under cat2
  • -- post under cat2
  • -- post under cat2

I know I can use wp_list_categories() to list categories, but how can I achieve to list also the posts under the respective categories, below an example what I want to achieve:

  • category1
  • -- post under cat1
  • -- post under cat1
  • -- post under cat1
  • category2
  • -- post under cat2
  • -- post under cat2
  • -- post under cat2
Share Improve this question edited Jan 23, 2021 at 17:32 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Jan 23, 2021 at 6:26 Botond VajnaBotond Vajna 4714 silver badges11 bronze badges 1
  • 1 In the code where you output the categories you're getting, you'd then want to run a wp_query for each one to get the posts. That's the best I can offer without seeing any code whatsoever. I also think that you'd be better off with get_categories() so you don't have to fight with the formatting. developer.wordpress/reference/functions/get_categories – Tony Djukic Commented Jan 23, 2021 at 15:02
Add a comment  | 

1 Answer 1

Reset to default 0

Finally I resolved the solution this way:

$hg_categories = get_categories();

            foreach($hg_categories as $hg_category) {
                echo '<h3>' . $hg_category -> name . '</h3>';
                $hg_posts = get_posts(array('numberposts' => -1, 'category' => $hg_category -> cat_ID));
                foreach ($hg_posts as $hg_post) {

                    if ($hg_post -> ID == get_the_ID()) {
                        echo '<li class = "current-post"><a href = "';
                        } else {
                        echo '<li><a href = "';
                    }                   
                        echo get_permalink ($hg_post -> ID);
                     echo '">';
                        echo $hg_post -> post_title;
                    echo '</a></li>';
                }
            }

if anyone have a better solution, please let me know, thank you.

本文标签: List categories with posts