Share

Display related posts in a definable amount of columns.

This function will add a shortcode that returns lists of related posts. The posts are formatted in a table like manner. You can send attributes to control the number of results, number of columns and you can opt to show or not show thumbnails and / or the excerpt.

The Code

There’s a little bit of CSS required too. Add this to your custom CSS file or child theme style.css. This is just enough to tidy up the output. You might want to customise it further to fit your design. The min-width:150px is to make the columns collapse and not get too thin on mobile devices. You might want to play with this value.

Parameters

You can specify the following parameters in the shortcode.

  • ‘max’ = The number of results returned (default 3)
  • ‘col’ = The number of columns wide (default 3)
  • ‘thumbnail’ = true/false to display post thumbnail (default true)
  • ‘excerpt’ = true/false to display excerpt (default true)
  • ‘excerptlength’ = max number of words in excerpt (default 20)

The posts are related by post tags, so make sure you set some..

Usage

You can now use the shortcode in your posts, like so:

[relatedposts] // This is the default (3 posts, 3 columns)
[relatedposts col=1 max=1 excerpt=false] // single post, full width, without the excerpt

If you wanted to call the function from php, for example your single.php template, you could do so like this:

This is the actual code I am using for my related posts.

Share