Let’s assume that I have the following posts with the following titles:
- PostA (is assigned to the ‘category 1’)
- PostX (category 2)
- PostB (category 1)
- PostC (category 1)
- PostD (category 1)
- PostY (category 2)
- PostE (category 1)
…
When a visitor will read the PostC, how can I display in the sidebar:
Previous Posts:
‘PostA’ (these are links here, of course)
‘PostB’
Next Posts:
‘PostD’
‘PostE’
IOW the previous and the next 2 posts from the same category. (If a post has more categories we will choose the 1st one or the last one – it doesn’t matter very much).
Also, if it is impossible to display the prev & next two posts it is acceptable also only one previous and next post. (I know that there are some WP functions for this but we prefer if it’s possible two posts).
Also, of course, we want to display the first ‘n’ characters from the title (let’s say 22). We don’t want to display a static text like ‘Next Post’ or similar.
TIA
The existing WordPress functions are only for displaying one previous or next post. I quickly wrote functions to display any number of posts.
Paste the following in your theme functions.php file:
In your sidebar file, where you want to display the posts, use
custom_adjacent_posts_links( true );
to display the two previous posts in the same category andcustom_adjacent_posts_links( true, false );
to display the next two posts in the same category.