How to separate posts by categories?

In the loop you’ll want to get the posts terms. Then instead of echo’ing, return the output and group it into an array where the keys are the categories. Then loop through the grouped array and output your categories and related posts. Something similar to:

// to hold and sort your output
$categories = array();

// loop through posts
while( $query->have_posts() ){

    // get the posts terms
    $terms = wp_get_post_terms(..
    $firstTerm = $terms[0];

    // see if the first term is defined in our holder
    if (!isset($categories[$firstTerm->name])) {
        $categories[$firstTerm->name] = array();
    }

    // ..

    $categories[$firstTerm->name][] = display_layout($page,$image);
}

Your display_layout() function would return your html instead of echoing.

Then you’d loop through $categories for your output:

foreach ($categories as $catName => $catItems) {
    echo "<strong>{$catName}</strong>";
    foreach ($catItems as $catItem) {
        echo $catItem;
    }
}

This isn’t a copy/paste answer, it’s just an idea for the logic of storing and sorting your values in an array – please keep in mind that you will want to:

  • use better logic than “first term”, as the first term won’t necessarily be 12 or 30 (unless you only did one-term-per-post – but that still leaves high probability of human error), you’ll want to loop through all the terms and see if it contains a $cat value
  • use IDs instead of strings for the array keys, $firstTerm->term_id instead of $firstTerm->name, finding a different way of carrying over the name value.
  • wrap this in a cache so each page load isn’t doing a ton of queries

error code: 523