I don’t offer much code to members, but I have long struggled with wrangling Jetpack’s related posts, so I figured I’d share some code that I used to finally do so today.
By default, you know what Jetpack’s related posts output is, right? It’s not too sexy. I turned it into this, and made it responsive of course:
Much better I think, though it may not look that much better at first glance.
Jetpack has a page on customizing the output, but it’s a bit all over the place. I wanted to do the following:
- Filter the headline (and remove that markup that causes the silly underline and funky text, as do the share buttons).
- Change the return image size to be larger, so I could make the articles a larger width (1200px in my case).
- Add a default image for when one isn’t available (sample code just points to the theme screenshot).
- Not output the posts in the content, so I could output them in the theme template.
- Make the responsive views better, and override the janky styles.
So that’s what the gist shows. There are files for the CSS (beware of my custom Sass variables), the functions you need to make these adjustments, and re-inserting the related posts in the template.
There were a couple of gotchas.
One, is that CSS. Jeez. It’s a big hot mess, but I promise you my specificity is the way it is so I could override Jetpack’s very, very opinionated markup and styles. Hopefully my targeting can help you. I tried to comment it well.
The Jetpack help articles don’t always account for if Jetpack isn’t active, or more likely, that a module is inactive, or even more annoying, if it is in development mode. That check for the related posts class becomes pretty important when in dev mode.
You’ll still need to enable the “visually striking” mode or whatever it’s called in the settings.
In the end, I was able to wrangle it to look pretty good, and now related posts can be output wherever I want.