The following code was provided in another question but doesn't seem to be working. Basically I have 4 post types (deals, accommodation, articles, attractions) and I would like to show a list of post types relating to a common taxonomy (destination) and use a header to seperate each taxonomy.

Destination: London
London Attractions

London Articles

London Deals


Any ideas on this? I have added this to taxonomy-destination.php but it seems to just hang.

$post_type = '';
while (has_posts()): the_post;

if (get_post_type() !== $post_type) {
    // print the header for the post type
    // maybe something like this...
    echo '<h2>', esc_html(get_post_type_object(get_post_type())->label)), '</h2>';

// do stuff with the current post

$post_type = get_post_type();


First thing's first, correctly indent your code. Your editor/IDE should have auto-magical auto-indenting tools. Use them, they're there for a reason, they're not just some developers high and mighty opinions of beautiful code.

Moving on,

Instead of echoing them out, put them in arrays then after the loop do your echo'ing out of each


// this will contains arrays representing all posts of each type
$post_types = array();

// We will now use our main loop to collect data ( not print it )
while (has_posts()){ // use braces, the while(): endwhile; syntax doesn't play nice with editors and the highlighting

    $type = get_post_type();
    // we may never have come across this type of post before, so make sure there's an empty array ready to receive the content
    if( !isset($post_types[$type]) )
        $post_types[$type] = array();

    // now create the content for this post, and insert it into the array filed under the relevant post type
    $post_content = '<li>'.get_the_title().'</li>';

    // notice how [] will append to the end of the array without you having to figure out indexes etc
    $post_types[$type][] = $post_content;

// now we've done our main loop, lets process the data we collected and display it
foreach ( $post_types as $type => $posts ) {
    // get the post types label
    $label = get_post_type_object(get_post_type())->label;
    echo '<h2>'.$label.'</h2>';

    // display this post types content
    echo '<ul>';
    foreach($posts as $post_content ) {
        echo $post_content;
    echo '</ul>';

This should give you headings containing the post type, followed by an unordered list containing posts of that type.

Now that you know how to separate the posts, and that you don't need to echo them you can save them in variables and manipulate them later, this is now purely a PHP question. Consider using output buffers to simplify the juggling of strings

| improve this answer | |

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.