A site I’ve been working on had a list of “recent posts” displaying underneath the main content. The feature used a WP_Query loop to display an image, title, and author link for each recent post.
The client wanted to update this to use a “related posts” algorithm instead, but didn’t want to change anything else about the design or display. That got me curious if it would be possible to fetch the IDs from the Related Posts module in JetPack, but then run them through WP_Query to output the existing custom markup.
Related Posts with Fallback
Here’s the code I came up with. If the JetPack Related Posts module is active and results are returned, it builds an array of post IDs in $related_posts and queries for those. If not, the query returns recent posts.
[gist id=”15469fd39f7c7b9bdaf4″ file=”related.php”]
Prevent JetPack from Displaying Related Posts
To prevent JetPack from automatically inserting its own related posts markup, you’ll need to use this filter:
[gist id=”15469fd39f7c7b9bdaf4″ file=”jetpack.php”]
If you want to prevent JetPack from outputting the stylesheets and JS for Related Posts, you’ll need to use a few more filters. JetPack concatenates this all by default, so you’d be losing the concatenation if want to strip out specific scripts and styles. If your server is running HTTP2, that would definitely be a performance boost- but otherwise I’m not sure if the trade off between HTTP requests and page weight would necessarily be worth it.
hey Devin thanks for the wonderful tutorial .. I am facing one issue i.e if i change the showposts count to other than 3 the query returns unexpected results
Hey Devin,
Thanks for this wonderful tips, Could you please give an idea how to display popular posts like this? I mean , by using jetpack
Hi! Great code! I need some help with one thing and I hope you can help me. As additional to the 3 related posts my sticky posts also shows in the related post section. Is there a possibility to exclude them?
/Patrik
https://jetpack.com/support/related-posts/customize-related-posts/#exclude-sticky