Query by JetPack Related Posts

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.

view raw related.php hosted with ❤ by GitHub

Prevent JetPack from Displaying Related Posts

To prevent JetPack from automatically inserting its own related posts markup, you’ll need to use this filter:

<?php
/**
* Prevents Related Posts from displaying in content area
*/
function prefix_remove_rp() {
if ( class_exists( 'Jetpack_RelatedPosts' ) ) {
$jprp = Jetpack_RelatedPosts::init();
$callback = array( $jprp, 'filter_add_target_to_dom' );
remove_filter( 'the_content', $callback, 40 );
}
}
add_filter( 'wp', 'prefix_remove_rp', 20 );
view raw jetpack.php hosted with ❤ by GitHub

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.

About Devin

I'm a WordPress developer based in Austin, Texas. I run a little theme shop called DevPress and work for a startup called Nano. Find me on twitter @devinsays.

2 Responses

  1. Amritanshu Kalia

    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

Leave a Reply