StylizedWeb

Subscribe to our updates:

A Design, WordPress and Tutorials Blog.

Dedicated to helping you learn the art and science of the web.

query_posts() Pagination problem

Ok, this has bothered me for a long time and now i have finally found a solution for it thanks to Kafkaesqui moderator on WordPress Support. As the title says when you are using a query_posts() to exclude, include categories or what ever you want pagination dosen't work it shows same posts on every page (This is for all pages that use query_posts not just index, so it's for templates etc...)

Where's the problem? query_posts() is a powerful function, but in this situation it has a flaw: it overrides nearly everything in the standard posts object query, including what the paged offset is.

How to fix it? To get proper pagination with query_posts() we need to recreate it through the 'paged' parameter or query. Best way to do this is to ask WordPress for the "page" we happen to be on, and use that as our 'paged' value. There's the code for it

  1.  
  2. <?php if (have_posts()) : ?>
  3. <?php query_posts("category_name=somecat"); ?>
  4. <?php while (have_posts()) : the_post(); ?>
  5.  
  6. replace with
  7.  
  8. <?php if (have_posts()) : ?>
  9. <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts("category_name=somecat&paged=$paged"); ?>
  10. <?php while (have_posts()) : the_post(); ?>
  11.  

And that's it! The $paged = line above uses what's called a ternary operator to test whether the 'paged' query variable is available. If it is, $paged receives its value. If it isn't, we assume we're on the first page and assign it '1'. Then we tell query_posts() what page we're on with the addition of &paged=$paged.

Leave a comment on Stylized Web Have some feedback? Leave a comment

199 Comments So Far

  1. Nice… now my gallery page on my new wp-theme works as it should. Alright! :)

  2. Worked a charm thank you :)

  3. from a solid starting point. Basic is infact many templates in one using a single stylesheet. By adding/removing small snippets of code from the html, Basic can go from a fluid 3 column web template for a fixed

  4. By Alberto Harres Rocha posted on October 4, 2011 at 10:32 pm

    WICH FILE I EDIT THIS??

    NOBODY TOLD THIS =((((

    help!!!!

  5. wow amazing i love it ..perfect..

  6. wow amazing i love it ..perfect.

  7. Was going round in circles with this – thanks for the tip. I adapted the code as wanted to display all posts in a blogroll:

    In answer to Alberto – you edit this in your page template file. In my case this was page-blog.php

  8. Thank you for this solution!
    :-)

  9. Pingback: WordPress主题设计笔记 » 虾子酱油学习网页设计

  10. Great solution! Thank you very much!

  11. Awesomenessssssssssssssss.

  12. Excellent , everything works again now!

    Thanks

  13. In A, B, C, high levels of vitamins and beta carotene barındıran­African Mango, form meets guidelines as well as the effect of contributi­ng to the beauty of your hair and skin. Beta Carotene, to ensure the beauty of the skin, night vision to strengthen the immune system against disorders, a variety of infections contribute to the substance.­Those who want to enter the world healthy and permanent form, which is a product of choice for African Mango, now in Turkey. Because people prefer to use a 100% herbal product that helps people to enter the African Mango form a single product.Hii Thanks…
    http://www­.africanma­ngosiparis­.com/

  14. Those who want to enter the world healthy and permanent form, which is a product of choice for African Mango, now in Turkey. Because people prefer to use a 100% herbal product that helps people to enter the African Mango form a single product.

  15. Thanks, man. That was killing me! $##$A%#$%$$!!!!!

  16. Thanks for codes

  17. Thank you, this worked exactly as I’d hoped.

    Just a note for others: This is the correct solution.

    Thanks!

  18. hello i tryed to apply your code but didnt worked

    im having problems with pagination in a template wordpress file – im not using it as my home page – its just a template page that show some categories.

    found a lot of answers in internet but none worked – and also your post is the only i found talking specific about template page

    maybe you can help me to find what im doing wrong ..

    this is the page im talking about:

    http://www.travelcouture.com.br/?page_id=9

    my code:

    and also:

    <?php next_posts_link( __( '← Older posts’, ‘matala’ ) ); ?>
    <?php previous_posts_link( __( 'Newer posts →’, ‘matala’ ) ); ?>

    thanxx

  19. ops couldnt paste the code.. i think the page link is enough right ? if anyone have some clue im really desperate :S

  20. solved with the code below:

    really thanx

  21. By Sergiu posted on March 15, 2012 at 10:27 pm

    Like a charm. Thank you.
    Cheers!

  22. Pingback: Andrew Brennan | WordPress Query_Posts(), Pagination & “More”

  23. By Tejas posted on June 1, 2012 at 8:03 am

    Thanks a lot for the great tips

  24. By Bruno Cosmo posted on June 25, 2012 at 4:19 pm

    I dont have this:

    I just have this in my index.php:

  25. By Bruno Cosmo posted on June 25, 2012 at 4:21 pm

    I dont have this:

    I just have this in my index.php:

  26. By Bruno Cosmo posted on June 25, 2012 at 4:23 pm

    I dont have this:


    I just have this in my index.php:

  27. Holy crap, you are my savior. This worked perfectly with wp simple pagination!

  28. Pingback: Andrew Brennan: WordPress Query_Posts(), Pagination & “More”

  29. You saved my day! Thanks!

  30. By Gizzard posted on August 31, 2012 at 6:19 am

    Hi Dejan, I spent *hours* trying to solve this problem. Thanks a bundle for posting this solution, it worked perfectly! Cheers, Gizzard

  31. Thanks a lot….
    This is amazing…

  32. Thanks! Brilliant solution for my custom query!

  33. By Thomas posted on November 24, 2012 at 1:01 pm

    Hey, thanks man!

  34. I have classipress 3.1.5 on wordpress 3.5.1

    what file.php i have modified?

    thanks

  35. Really appreciate, thanks a lot.

  36. I’m amazed, I have to admit. Rarely do I encounter a blog that’s both equally
    educative and engaging, and let me tell you, you’ve hit the nail on the head. The problem is something too few folks are speaking intelligently about. I am very happy I found this in my search for something concerning this.

  37. I just like the helpful information you supply to your articles. I will bookmark your blog and check again here regularly. I’m slightly certain I’ll be informed plenty of new stuff right here! Good luck for the next!

  38. Hi there, just wanted to say, I liked this post. It was helpful. Keep on posting!

  39. Having read this I thought it was really enlightening.

    I appreciate you spending some time and effort to put
    this article together. I once again find myself personally spending a significant amount of time both reading and
    leaving comments. But so what, it was still worth it!

  40. By Michael posted on October 10, 2013 at 1:24 am

    I’m using Cleaner Business & Portfolio WordPress Theme.. which php file should I edit?
    Thanks

  41. It is the best time to make some plans for the future and it’s time to be happy.

    I’ve read this post and if I could I want to suggest you few interesting things or tips.
    Maybe you could write next articles referring to this article.
    I desire to read more things about it!

  42. Need for Speed: Rivals mettra en vedette un jeux similaire à un besoin de 2010
    Need for Speed: Hot Pursuit titre dans la franchise Need for
    Speed avec des voitures exotiques et de la police poursuites à haute vitesse.
    Les joueurs prennent le rôle d’un coureur ou
    un flic, avec de chaque côté de la loi offrant son propre ensemble de défis, les risques et les
    récompenses. Rivals mettra en vedette onze gadgets évolutifs tels que les PGE, ondes de choc et
    la possibilité de faire appel à des barrages routiers.
    Le jeu se déroule dans le une ville nomme ‘Redview County’, une zone de monde ouvert qui est l’hôte de déchets entre police et aux voleurs.
    Le monde ouvert mettra en vedette une structure similaire à un besoin de 2012 for Speed:
    Most Wanted, avec plusieurs sauts, des pièges de
    vitesse et les voitures à débloquer.

  43. Hello, I would like to subscribe for this web site to take
    most recent updates, so where can i do it please help.

    Also visit my web page: call of duty ghosts multiplayer crac (German)

  44. Бързи заеми и всички видове бързи кредити
    Сайт за бързи заеми и потребителски
    кредити в България
    Пари назаем до 24 часа с бърз кредит
    В този уеб сайт ще намерите списък на фирми предлагащи бърз заем,
    в които получавате парите до 24 часа, предложения за бърз потребителски кредит
    над 399 лв, както и актуални промоции , списък с офисите на компаниите по
    градове, микрокредити за малкия бизнес,
    удобен филтър за бързо намиране на най-добрата оферта, калкулатор, услуги с изцяло онлайн процес за кандидатстване и взимане на парите, полезна информация.

    Feel free to visit my site … банки кредити

  45. В повечето случаи бързо финансиране
    със сигурност са наистина скъпо .
    В крайна сметка плащат годишен норма
    цени че ще бъде многобройни 100 лева
    или така % . За да дам един пример може би ще може прекарат 20 лева цена до назаем 100.00 лева
    за няколко няколко седмици . Потребителят федерацията на България има някои
    хубави прилични изчисления
    изследване бързо финансиране да други
    възможности . . се налага да плащат над 1000
    Проценти всъщност не е необичайно все пак бихте
    компенсира 426 % в Наистина бързо .
    кредитна

    Also visit my web site; кредитна институция

  46. You can definitely see your expertise within the work
    you write. The sector hopes for even more passionate writers like you who are not afraid to mention how they
    believe. At all times go after your heart.

  47. By PiXEL posted on June 18, 2014 at 7:19 pm

    Perfectly Answer

  48. It’s a shame you don’t have a donate button! I’d certainly donate to this superb blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will share this blog with my Facebook group. Talk soon!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>