Hi MattV,
If a post only has two related posts this plugin can’t find other related posts for it. You can however add unrelated posts to finish the row.
Try it with this in your (child) theme’s functions.php
add_filter( 'related_posts_by_taxonomy', 'rpbt_finish_related_row', 10, 4 );
function rpbt_finish_related_row( $results, $post_id, $taxonomies, $args ) {
$columns = 3;
if ( empty( $results ) ) {
return $results;
}
$post_ids = wp_list_pluck( $results, 'ID' );
$count = count( $post_ids );
if ( ( $count % $columns ) !== 0 ) {
// calculate the remainder for the row
$remainder = ( floor( $count / $columns ) * $columns ) + $columns - $count;
// add current post id
$post_ids[] = $post_id;
$_args = array(
'posts_per_page' => $remainder,
'post__not_in' => $post_ids,
'meta_query' => array( array( 'key' => '_thumbnail_id' ) ),
'orderby' => 'rand',
);
$related_extra = get_posts( $_args );
$results = array_merge( $results, $related_extra );
}
return $results;
}
btw:
consider creating a child theme instead of editing your theme directly – if you upgrade the theme all your modifications will be lost. Or create a plugin with the code above.
Thread Starter
MattV
(@mattv)
Thanks for taking the time to provide such a great answer. I´ll try it tomorrow!
You’re welcome. Let me know if it does the job.