0

I'm trying to inject a post while the loop is running. This post will be injected on a condition, so if(x == j){ //inject post here } I see this would seem easy to do, but i have a posts_per_page argument in my query to use for paginating and i'm afraid that injecting a post would mess it up.

Thanks in advance for any help!

1
  • Could you elaborate on logic required? Inserting post non-consistently (only on some pages) would indeed make challenging to offset pagination right.
    – Rarst
    Jun 12, 2013 at 20:15

1 Answer 1

0

I am assuming you are doing something like this:

if (have_posts()) {
  while (have_posts()) {
    the_post();
    if(x == j){ //inject post here }
  }
}

Injecting a post inside the Loop like that will cause the post count for that page to differ from the posts_per_page value, but it will not break pagination (which seems to be your primary question). Pagination operates on the main query (usually) and that will not be altered by your insertion.

I don't know how you are retrieving the additional post data but if you are not careful you can break things with that.

4
  • thanks @s_ha_dum but here's the problem. so say i am displaying 16 posts per page. and they are in a grid 4x4. So you could imagine that it would paginate after four rows have been completed. I am not sure if the pagination will get that because of adding a square in the grid.
    – KT.
    Jun 12, 2013 at 16:16
  • You asked about pagination. How your 4x4 grid works is another issue. I think you are going to need to do some math. Say you want 16 total with 4 inserted per page, then set posts_per_page to 12 and insert the rest. Nonetheless, pagination strictly speaking should not be effected.
    – s_ha_dum
    Jun 12, 2013 at 18:10
  • The number of inserted posts will vary from page to page so this solution cannot work. I am trying to look for a way now to just break the page when i hit 16 and continue on next page but there seems to be none.
    – KT.
    Jun 13, 2013 at 8:20
  • The query has to be able to keep track of where it is in the result set. If you are changing posts_per_page on every page of the result set, which is what this amounts to, the query is going to be hopelessly lost. If you know how many inserted posts you have early enough to use pre_get_posts you may be able to juggle things with some clever math, but I am not sure you'll ever get the next and previous posts links to work right, and you certainly won't get and "total page count" navigation working.
    – s_ha_dum
    Jun 13, 2013 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.