Support

Account

Home Forums General Issues Sort by post category and then by date

Solved

Sort by post category and then by date

  • All posts have categories and dates.
    I want to sort them by categories (meta-value), which are strings.
    Afterwards, I want to sort them by year (meta-value-num).

    This is what I have now:

    <?php
    $allPosts = new WP_Query(array(
    ‘posts_per_page’ => -1,
    ‘post_type’ => ‘intervention’,
    ‘orderby’ => ‘meta_value’,
    ‘meta_key’ => ‘publication_category’,
    ‘order’ => ‘ASC’
    ));

    while($allPosts->have_posts()){
    $allPosts->the_post();

    //Display posts ordered by category and inside categories organise by dates

    }
    ?>

    How can I solve this?
    Thanks to the community!

Sort by post category and then by date

  • It is not possible using a single WP_Query to sort posts by term and then by date, or visa-versa.

    You can do this by doing multiple queries, one for each term.

    Another option would be do sort the post array returned in the query using PHP usort() or one of the other PHP array sorting function.

  • Great, thanks!
    This is how it was solved.

    
    <?php
    $allPosts = new WP_Query(array(
        'posts_per_page' => -1,
        'post_type' => 'intervention',
        'orderby' => 'meta_value',
        'meta_key' => 'publication_category',
        'order' => 'ASC'
    ));
    
    // Get the posts
    $posts = $allPosts->posts;
    
    // Define custom sorting function
    function custom_sort($a, $b) {
        // First, compare by publication category
        $categoryA = strtolower(get_post_meta($a->ID, 'publication_category', true));
        $categoryB = strtolower(get_post_meta($b->ID, 'publication_category', true));
    
        // Compare categories alphabetically
        $categoryComparison = strcmp($categoryA, $categoryB);
    
        // If categories are the same, compare by publication year
        if ($categoryComparison == 0) {
            $yearA = intval(get_post_meta($a->ID, 'year', true));
            $yearB = intval(get_post_meta($b->ID, 'year', true));
            return $yearB - $yearA;
        }
    
        return $categoryComparison;
    }
    
    // Sort the posts array using the custom sorting function
    usort($posts, 'custom_sort');
    
    foreach ($posts as $post) {
        setup_postdata($post);
    
       //Display posts ordered by category and inside categories organise by dates
        
        // Reset post data
        wp_reset_postdata();
        ?>
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.