I have a WordPress database with three categories:

ID 3 : Europe

ID 4 : France (child of 3)

ID 5 : Paris (child of 4)

I now need to display all posts under their respective category, like this:

EUROPE

Post 1

Post 2

Post 3

FRANCE

Post 1

Post 3

PARIS

Post 3

  • Post 1 was published under France
  • Post 2 was published under Europe
  • Post 3 was published under Paris

Can you please confirm I am doing it right like this?

<?php
    $args = array('cat' => 3);
    $category_posts = new WP_Query($args);
?>
<!-- Show EUROPE block, so just loop, no check -->
<?php
    while($category_posts->have_posts()) : $category_posts->the_post();
        the_title("<br />");
    endwhile;
?>          
<!-- Show FRANCE block, check category name -->
<?php
    while($category_posts->have_posts()) : $category_posts->the_post();
        if (strpos(get_the_category()[0]->cat_name,'France') !== false)
            the_title("<br />");
    endwhile;
?>
<!-- Show PARIS block, check category name -->
<?php
    while($category_posts->have_posts()) : $category_posts->the_post();
        if (strpos(get_the_category()[0]->cat_name,'Paris') !== false)
            the_title("<br />");
    endwhile;
?>          
  • HTML formatting omitted from above code.

In poor words, I am calling WP_Query only once and then I loop, checking for the category name “France” and “Paris” for the France and Paris blocks. Is there a better way to do it? Would I cause any performance issues if I call WP_Query three times instead?

Thank you!

Read more here: How to retrieve posts from parent category, splitting them per children when displayed?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.

Related Wordpress search:

, , , , , ,

Wordpress related questions and answers: