ok1ha
ok1ha

Reputation: 637

Group Posts by meta_query

I'm trying to group my posts by a meta value, and can't seem to figure it out. My query below just returns "featured" posts. I would like the query to return all posts, but have the "featured" results before the rest.

Any ideas?

 $args = array(
    'posts_per_page' => '20',
    'paged' => $current_page,
    'meta_query' => array(
        array(
            'key' => 'tags',
            'value' => 'featured',
            'compare' => 'like'
        )
    ),
    'order_by' => 'date',
    'order' => 'DESC'
 ); 

Upvotes: 0

Views: 1100

Answers (1)

Pieter Goosen
Pieter Goosen

Reputation: 9951

Your answer is rewind_posts(). Run your query to get all the posts, run your loop and filter out all posts which is not featured, rewind the loop, rerun the loop and filter out featured posts.

Something like this will do

$args = [
// Your query arguments to get all postst
];
$q = new WP_Query( $args );

if ( $q->have_posts() ) {
    while ( $q->have_posts() ) {
    $q->the_post();

        if ( get_post_meta( $post->ID, 'tags', true ) == 'featured' ) {

            // Run your loop for featured posts

        }

    }

    $q->rewind_posts(); // Rewind the loop to rerun it

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

        if ( get_post_meta( $post->ID, 'tags', true ) != 'featured' ) {

           // Run your loop for non featured posts

        }
    }
    wp_reset_postdata();
}

Upvotes: 1

Related Questions