Posted on

Related Posts

Related posts is a popular feature, as it keeps the users engaged and offers them a new direction to continue to within your site, keeping the users on your site for a longer period of time.

There are many plugins that do related posts, but many have issues. Generating related posts can be a performance drain, the related posts may be irrelevant and there may not be enough control over how the related posts are managed and kept up to date.

Relevanssi Premium offers related posts and takes care all of these issues:

  1. Performance: Relevanssi uses transient caches to store the related posts for two weeks. The related posts are loaded from the transient cache very quickly, without any performance loss on the site. And don’t worry about the long cache periods: if a post is removed, Relevanssi will purge all related caches so that it will disappear from related posts right away.
  2. Relevance: Relevanssi uses the Relevanssi search index to look for related posts. This ensures the related posts are really related. Relevanssi can use titles, tags, categories and other taxonomy terms to match the related posts. You can also define custom keywords for each post, force particular posts to appear in the related posts and also block posts.
  3. Control: Relevanssi makes sure the caches are flushed whenever necessary. You can also manually flush all related posts caches and there’s also a WP CLI command for regenerating all related posts.

Setting up the related posts

To get started, navigate to the Relevanssi settings (Settings > Relevanssi Premium) and go to the Related tab, check the “Enable related posts” checkbox to enable related posts in the first place.

To see related posts on your site, you can check the post types you want in the “Automatically add to these post types” settings to have Relevanssi automatically append the related posts to your posts. This is done using the the_content filter hook, which should place the related posts at the bottom of the posts.

Enabling the related posts

The Keyword sources option will determine which content is used to find the related posts. Title is a good default option. You can also add taxonomies, like posts and categories. Using taxonomies requires that Relevanssi is set to index the taxonomy; you can adjust that on the Relevanssi indexing settings page.

You can choose which post types are used for the related posts. “Matching post type” means that for posts, posts are used, for pages pages and so on. If you choose another post type, all posts regardless of type will get that post type as recommendations.

You can also set the number of related posts shown and choose what happens if Relevanssi doesn’t find enough related posts: you can choose to use random posts or to leave the related posts empty.

Choosing the related posts

Adding the related posts manually

If you don’t want to automatically append the related posts to the posts, you can use the relevanssi_the_related_posts() function in your templates. The function will print out the related posts. If used without a parameter, it will use the global $post (and thus only works within The Loop), but you can also specify the post ID as a parameter for the function.

You can also use the shortcode relevanssi_related_posts to print out the related posts. You can specify the post ID as the parameter post_id, or specify nothing to use the global post.

Adjusting the look of the related posts

Relevanssi uses a template file to print out the related posts. The default template can be found in the /premium/templates/relevanssi-related.php file in the Relevanssi folder. If you use the default template, you can adjust the look of the results from the settings page: you can choose whether Relevanssi displays the title, the thumbnail or the excerpt for the posts. Also, for thumbnails, you can set up a default thumbnail in case the post doesn’t have a thumbnail.

You can also set up the minimum width of the related posts. Relevanssi uses a simple CSS grid to lay out the related posts, and this setting is used to adjust the minimum width of each element. Experiment with different values to see what works.

Style settings

If you want to to style the related posts, everything is wrapped inside div#relevanssi_related, the header is in div.relevanssi_related_grid_header and the grid itself is in div#relevanssi_related_grid. Each post is a div.relevanssi_related_post.

If you want to make bigger modifications, you can create your own template. Relevanssi will look for the relevanssi-related.php template inside the current theme templates folder and if it finds one, will use that instead of the default template. When creating your own template it’s best to start with the default template and make the changes you want, while keeping the basic loop structure intact to make sure everything works as expected.

Single post settings

There are also Related posts controls on post edit pages. You can disable the auto-append for the post – for example if you have related posts automatically added to all pages, there are probably pages where you don’t want them, like the front page. You can also disable to post so that it’s never used as a related post for another post.

You can also specify keywords that are used to fetch the related posts for that post. Those keywords are added to the other keywords in use. If you want a specific post to appear as a related post, you can list the post ID.

The widget will also show the current list of related posts. Changing the settings should refresh the list right away. If there’s a post you don’t want to see on the list, just click “Not this” to remove it from the list.

Single post settings

Advanced topics

The rest of this page is not required for using the related posts feature, but may be interesting from technical standpoints or for sorting out problems.

Caching

Relevanssi caches the related posts for each post. The caches are stored in transients and are kept for two weeks before they expire. The cache includes the whole related posts element, so once it’s in the cache, it’s lightning fast to serve (especially with a setup that stores the transients in memory).

Relevanssi also stores the post IDs of the related posts in a custom field (_relevanssi_related_posts); this is used by Relevanssi in the admin dashboard, and can be used for other purposes as well.

If a post is made non-public, Relevanssi finds all caches where the post is included and flushes those caches. This makes it possible for Relevanssi to keep long expiry periods for the caches, while making sure drafts and trashed posts don’t appear in the related posts.

You can flush all the caches from the Relevanssi related posts settings page.

Cache settings

Adjusting the location of automatically added related posts

If you have other plugins that use the_content to add things to the bottom of the posts – like social media share buttons – you can adjust the priority and thus the location of the related posts using the relevanssi_related_priority filter hook. The default priority is 99. To move the related posts later, you can do this:

add_filter( 'relevanssi_related_priority', function() { return 999; } );

If you want the related posts to appear earlier, do the same but adjust the priority to a smaller number.

Improving the performance

If your keyword sources are rich and your related posts are using lots of words (maybe closer to ten words), searching may become a bit too heavy. This is not a problem in general searches, because very few users use this many search terms, but in Related posts searches, this can be a problem.

One way to improve performance in these cases is setting the throttle to a much tighter setting for Related posts searches – here it’s not such a big deal if some relevant posts go missing occasionally, but the performance boost from the tighter throttle can make a big difference.

Throttle – and any other Relevanssi options – can be adjusted with the help of pre_relevanssi_related and post_relevanssi_related actions, which run before and after the Related posts search. Change the options in the pre action and return them to normal in the post action. Here’s an example of how to adjust the throttle to 50 for Related posts searches and how to modify the weights so that tags get a heavier weight in Related posts searches.

add_action( 'pre_relevanssi_related', 'rlv_pre_related_posts' );
function rlv_pre_related_posts() {
	// Make sure throttle is enabled and set it to a low value to avoid memory
	// issues if there are lots of keywords in the related posts search. If you
	// have the throttle enabled otherwise, this part is not necessary.
	global $relevanssi_throttle_enabled;
	$relevanssi_throttle_enabled = get_option( 'relevanssi_throttle' );
	if ( empty( $relevanssi_throttle_enabled ) || 'off' === $relevanssi_throttle_enabled ) {
		update_option( 'relevanssi_throttle', 'on' );
	}
 
        // This doesn't need undoing, because we don't change the option, just use
	// the pre_option to change the value on the fly.
	add_filter( 'pre_option_relevanssi_throttle_limit', function() { return 50; } );
 
	// Adjust the weight for tags to 20 to make tag matches more important.
	global $relevanssi_post_type_weights;
	$relevanssi_post_type_weights = get_option( 'relevanssi_post_type_weights' );
	$new_weights                  = $relevanssi_post_type_weights;
 
	$new_weights['post_tagged_with_post_tag'] = 20;
	update_option( 'relevanssi_post_type_weights', $new_weights );
}
 
add_action( 'post_relevanssi_related', 'rlv_post_related_posts' );
function rlv_post_related_posts() {
	// Disable the throttle if it should be disabled by default.
	global $relevanssi_throttle_enabled;
	if ( empty( $throttle_enabled ) || 'off' === $throttle_enabled ) {
		update_option( 'relevanssi_throttle', 'off' );
	}
 
	// Set the weights back to normal.
	global $relevanssi_post_type_weights;
	update_option( 'relevanssi_post_type_weights', $relevanssi_post_type_weights );
}

Warning about relevanssi_hits_filter filter hooks

If you have a filtering function on relevanssi_hits_filter it may interfere with the related posts. Often these filter functions assume that the hits array has complete post objects and may check for $hit->post_type to sort the results by post type. However, with related posts, the hits array contains just post ID’s and not complete post objects.

If you want to use the filter function with the related posts, it needs to be built in a way that works both with post objects and post ID’s. Here’s how the Relevanssi relevanssi_wpml_filter() function (in lib/compatibility/wpml.php) handles this:

foreach ( $hits[0] as $hit ) {
	$original_hit = $hit;
	if ( is_numeric( $hit ) ) {
		// In case "fields" is set to "ids", fetch the post object we need.
		$original_hit = $hit;
		$hit          = get_post( $hit );
	}
	if ( ! isset( $hit->post_content ) ) {
		// The "fields" is set to "id=>parent".
		$original_hit = $hit;
		$hit          = get_post( $hit->ID );
	}

Now the filter can use the full post object in $hit to examine and filter the post, and when the post is saved in the results array, $original_hit is used instead of $hit to make sure the right format is used.

If the filter function is something you don’t need for the related posts, it’s easiest just to disable it:

add_action( 'pre_relevanssi_related', function() { remove_filter( 'relevanssi_hits_filter', 'function_name' ); } );

This action hook runs before the related posts queries and can be used to disable unwanted filters.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.