How do you go about adding related posts? Do you code it? Do you have a repo you can recommend in that case? Or do you prefer using a plugin and which case which one? Trying to keep a theme in a Trellis Bedrock setup as lightweight as possible so would appreciate your insights here.
I do know YARP, but I am wondering if a plugin is really necessary and if so if this is the right choice.
As usual, the answer is “it depends”.
I would start by asking myself: "what is a sensible way to provide related posts in this specific website, for this specific audience?"
Another important question is: should it be automatic, manual, a bit of both? Talk to your end-user, (s)he’ll have a good opinion about that. When you post 20 articles every day, you’d rather go for automatic. If it’s one article a week, you’d go for manual.
Once you know, you can either make it using a custom query (using a custom call of WP_Query() ;
) or use the YARP plugin. Either way, having several plugins is not bad per se. It depends which plugins (badly coded, or pieces of coding beauty). I haven’t reviewed YARP, so do test it thoroughly (also: check the plugin’s support requests on the WP forum, it’s a good way to get a feel how it fares in the long run).
Here is a way I did it recently, on a website using ACF Pro (hence the get_field()
function calls), since the end-user chose to cherry pick the related posts manually:
function print_related_posts(){
if (is_admin() || !is_single() || !class_exists('acf')){
return '';
}
$related_posts = get_field('related_posts', get_the_ID() );
$title = get_field('related_posts_title', get_the_ID() );
if(count($related_posts) > 0 ){
$html ='<div class="u-related-posts share_box clearfix"><h3>';
$html .= (!empty($title)) ? $title : 'Suggestions:';
$html .= '</h3><ul class="blog">';
global $post;
ob_start();
foreach ($related_posts as $post){
setup_postdata($post);
get_template_part('template-parts/teaser', 'square');
}
wp_reset_postdata();
$html .= ob_get_contents();
ob_end_clean();
$html .= '</ul></div>';
}
return $html;
}