Categories: DevelopmentWordPress

WordPress + Query_Posts + Sticky + Pagination

We often have some posts that we would like to promote and keep at the first page of the blog. When you are using pagination, the sticky posts will be added to the standard posts, making the post count per page uneven.

If you want to keep your posts per page count consistent, there is a way to do that.

PREPARE PAGINATION

  1. global $paged;
  2.  
  3. if (!isset($paged) || !$paged){
  4.  $paged = 1;
  5. }
  6.  
  7. // Set posts per page
  8. $posts_per_page  = 8;
  9.  
  10. // Get sticky posts
  11. $sticky = get_option( 'sticky_posts' );

SWITCH QUERY FOR FIRST PAGE

  1. // First page and has stickies
  2. if($paged == 1 && !empty($sticky)) {
  3.  
  4.   $args = array(
  5.   'post_type' => 'post',
  6.   'paged' => $paged,
  7.   // Adjust posts per page by subtracting the amount of stickies
  8.   'posts_per_page' => $posts_per_page - count($sticky)
  9.  
  10.   );
  11.  
  12. }else{
  13.  
  14.   $args = array(
  15.   'post_type' => 'post',
  16.   'paged'               => $paged,
  17.   'posts_per_page' => $posts_per_page,
  18.   // making sure the 2nd page starts with the right post
  19.    'offset' => (($paged-1)*$posts_per_page) - count($sticky)
  20.   );
  21.  
  22. }
  23. // Do query
  24. query_posts($args);

Enjoy coding …

Alex

I am a full-stack developer. I love programming,  design and know my way around server architecture as well.  I would never feel complete, with one of these missing. I have a broad range of interests, that’s why I constantly dive into new technologies and expand my knowledge where ever required. Technologies are evolving fast and I enjoy using the latest. Apart from that, I am a peace loving guy who tries to have people around him that think the same.  I truly believe in the principle: “If you help someone, someone will help you, when you need it."

Recent Posts

B&B / Hotel Booking Solutions for WordPress | 2024

BOOKING SOLUTIONS 202x This is my take on a subset of booking, appointment, PMS or… Read More

4 weeks ago

WordPress Cron + WP-CLI + Ntfy

THE GOAL Create a system cron for WordPress, that is accessible and can be easily… Read More

2 months ago

2024 is here and now :)

2024, what's cooking? Slowly getting into the 2024 spirit. 3 projects coming to a close… Read More

4 months ago

2023 ends and whats next !

Short look back at 2023 This has been a busy and interesting year. I am… Read More

4 months ago

cubicFUSION Grid Tweaker – Elementor Grid made easy.

Elementor Pro provides grid containers as an experimental feature. The options provided are limited, when… Read More

5 months ago

Archaeology Travel Booth – Travel Innovation Summit 2023

Archaeology Travel is an online travel guide for people who enjoy exploring the world’s pasts.… Read More

6 months ago