I have a layout where I need to show the most recent post in a different layout/design component and remaining posts, needed to have a separate layout/design.
I also wanted to use pagination to show other posts instead of infinite scrolling because I do not prefer infinite scrolling.
Using the count modulus
was not going to be a viable option due to how the design needed to be implemented but I think it could work for someone with experience in PHP.
When using the offset
in the loop, it was changing on pagination so each page after the first page had different recent post.
This was troublesome but I think I have a solid working solution for having multiple loops it works for my needs.
I separated my loops by using the first loop as the standard (have-posts)
loop and the second loop ($custom_query)
.
The issue was firstly, getting the offset
to only work on the second loop ($custom_query)
.
I achieved this by finding code examples of using the pre_get_posts
and found_posts
functions to target only the home.php and not the main query. All of this was new to me, but I believe if you read over the code and visit the links in the code, you can start to understand (depending on your PHP level) what WordPress wants you to do to make this happen. (Run on sentence much? lol).
The next goal was to get the pagination to work without being failing. By failing I am referring to how in previous attemps, the pagination would not find additional posts based on the secondary query and just show previous content.
That is where the $wp_query
hack in the content-home.php
works. Also, I found by putting the // Pagination
code found in content-home.php
file after the wp_reset_postdata()
call, and resetting the $wp_query
hack after the paginate_links
function got the pagination to work as expected. Which is, pagination generates page links that show additional content from the secondary query/loop.
I am still learning PHP
and WordPress
and I know all of this code could be rewritten to be more performant: less database calls, smaller code size, .etc. So please, fork & modify and share. It makes us all better developers.