user1202292
user1202292

Reputation: 543

Offsetting posts and alterating a WP_query the correct way

I'm having some trouble with ordering a loop! I want to show posts in a Countdown style (5, 4, 3, 2, 1) but using metadata and user inputted data.

I have this data:

Post A with meta data (score = 2)
Post B with meta data (score = 4)
Post C with meta data (score = 6)
Post D with meta data (score = 8)
Post E with meta data (score = 10)

Example user wants to show a top 3 countdown, so $user_input = 3.

The page should then show: Post C, Post D, Post E. (ordered by meta score and showing the best score last).

I have a wp_query loop as so:

   $args = array('meta_key' => 'score', 'orderby' => 'meta_value_num', 'order' => 'ASC', 'posts_per_page' => $user_input);
   $qry= new WP_Query( $args );
        $count_posts = $qry->post_count; 
        $offset = $count_post - $user_input
        while ( $qry->have_posts()  ) : $qry->the_post();
              // echo stuff

It works, except that because it is set to order=ASC and posts per page is now set to 3 (when there are 5 posts in the category) it shows Post A, Post B, Post C. And that is what I need it to show except that it should be C,D,E.

I thought I needed to offset the wp_query, but I can't add an 'offset' into the args array because I don't know how many posts are in the category. I need to do a post_count after the WP_Query and substract user_input to know how many I need to offset by. So that's why I put the calculation for $offset.

My question is. How do I alter the WP_query the correct way? Is a

 query_posts('offset'.$offset.'&showposts'.$user_input)

after the offset is calculated a bad way of doing it because it is doing another query?

Is there a way to easy add a parameter to the wp_query after it has already been set?

Thanks guys

Upvotes: 0

Views: 1015

Answers (1)

kjetilh
kjetilh

Reputation: 4976

A quickfix would be to change the order in your query to 'DESC' instead of 'ASC'. This will get you the 3 biggest scores. Then you can fetch the posts in an array using $qry->get_posts() but they will still be in the wrong order. Simply do a array_reverse() to sort it in the order you want. The only difference in the loop is that you loop normally through the items like an array and use the setup_postdata() function instead of $qry->the_post()

<?php

// Set order to DESC
$args = array('meta_key' => 'score', 'orderby' => 'meta_value_num', 'order' => 'DESC', 'posts_per_page' => $user_input);

$qry = new WP_Query( $args );

// Fetch the posts and reverse it to get the wanted order
$posts = array_reverse( $qry->get_posts() ); 

foreach ( $posts as $post ) : setup_postdata( $post ); // sets up postdata in the same way as $qry->the_post();

    // ... 

endforeach; 

wp_reset_postdata(); // reset postdata after the loop

?>

Upvotes: 0

Related Questions