1

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
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.org/reference/functions/get_categories Jan 23 at 15:02
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.