This Pro tutorial shows how we can modify the parameters of a Bricks query to limit the posts to the previous two whilst cycling to the latest post if necessary when viewing single posts.
| Array Index | Post Number | Sample Post ID | Previous Posts |
|---|---|---|---|
| 0 | 7 (latest) | 16 | [6, 5] |
| 1 | 6 | 19 | [5, 4] |
| 2 | 5 | 24 | [4, 3] |
| 3 | 4 | 56 | [3, 2] |
| 4 | 3 | 83 | [2, 1] |
| 5 | 2 | 13 | [1, 7] |
| 6 | 1 (oldest) | 1 | [7, 6] |
Examples:
When on the post with ID 56, posts with IDs 83 and 13 will be shown.
When on the latest post i.e., post with ID 16, posts with IDs 19 and 24 will be shown.
When on the very first (or oldest) post i.e., post with ID 1, posts with IDs 16 and 19 will be shown.
Step 1
Edit your single post template with Bricks and add a Section.
Inside the Section’s Container, add a h2 Heading that reads say “Previous Posts”.
Add a Container and inside that a Block.
Check “Use query loop” on the Block.
Click the query icon.
Set Posts per page to 100 or a large enough number that is typically higher than the number of posts in the site. For example, if the site is only going to ever have 30 posts set this to say 40 or 50.
Add your desired elements like Post Title inside the Block.
At this stage, this will output all the posts in the site.
In the next step, we shall get the post IDs of the previous 2 posts and set this as the value of post__in query parameter.
Step 2
Add this in child theme‘s functions.php or a code snippets plugin:
add_filter( 'bricks/posts/query_vars', function( $query_vars, $settings, $element_id ) {
if ( $element_id === 'iobrur' ) {
// make an array of all (set a large enough number that the number of posts practically will not exceed) the post IDs
$all_post_ids = get_posts( array(
'fields' => 'ids',
'posts_per_page' => 500,
) );
// get index of the current post
$current_post_index = array_search( get_the_ID(), $all_post_ids );
// get the next 2 posts
$next_post_ids = array_slice( $all_post_ids, $current_post_index + 1, 2 );
// if there is only 1 next post, also get the first post
if ( count( $next_post_ids ) === 1 ) {
$next_post_ids[] = $all_post_ids[0];
}
// if there are 0 next posts, get the first 2 posts
if ( empty( $next_post_ids ) ) {
$next_post_ids = array_slice( $all_post_ids, 0, 2 );
}
$query_vars['no_found_rows'] = true;
$query_vars['update_post_meta_cache'] = false;
$query_vars['update_post_term_cache'] = false;
$query_vars['post__in'] = $next_post_ids;
}
return $query_vars;
}, 10, 3 );
Replace iobrur with the Bricks ID of your query loop element.
Reference
https://wesztyweb.com/efficient-database-query-optimizations-in-wordpress/