Rearranging posts based on categories

May be it’s a bad idea, but it’s the only.

Don’t print posts immediately, but collect them in different variables: one for category “test”, one for the rest.

<?php
$w_h = $w_d = $last = 0;
// init variables to concatenate content later
$primary_posts = $secondary_posts="";
// empty array to fill later
$category_names = array();
if (have_posts()) :
    while (have_posts()) :
        the_post();
        if ( date('Yz') == get_the_time('Yz') ) {
            if (!$w_d++) echo '<h6>Today</h6>';
        } elseif ( date('Yz')-1 == get_the_time('Yz') ) {
            if (!$w_h++) echo '<h6>Yesterday</h6>';
        } else {
            echo the_date('', '<h3>', '</h3>');
        };
        // get post categories
        $category_objects = get_the_category();
        foreach($category_objects as $category_object) {
            $category_names[] = $category_object->name;
        }
        // if posts belongs to category 'test'
        if( in_array('test', $category_names) ) {
            $primary_posts .= '<div class="post">Post of category "test"';
            // title, categories and excerpt goes here
            $primary_posts .= '</div><!-- .post -->';
        }
        else {
            $secondary_posts .= '<div class="post">Post of category other than "test"';
             // title, categories and excerpt goes here
            $secondary_posts .= '</div><!-- .post -->';
       }

    endwhile;
    // output all posts of category "test"
    echo $primary_posts;
    // output all posts of category other than "test"
    echo $secondary_posts;
endif;

Leave a Comment