Change Related Blog Posts To Be Based on Tags

This is a Developer Level doc.

If you're unfamiliar with PHP and/or editing files, codes and templates, as well as with resolving possible conflict, please seek help from a professional. Under our Support Policy, we don't provide support for modifications and customization.

/**
 * Alter single posts related section to display related items based on tags and NOT categories
 */
function myprefix_alter_related_posts_query_args( $args ) {

	// Remove category arguments
	$args['category__in'] = null;

	// Get post tags
	$tags = wp_get_post_terms( get_the_ID(), 'post_tag' );

	// If post has tags, create array of tag ids and query posts inside these tags
	if ( $tags ) {
		$tag_ids = array();
		foreach( $tags as $tag ) {
			$tag_ids[] = $tag->term_id;
		}
		$args['tag__in'] = $tag_ids;
	}

	// Return arguments
	return $args;

}
add_filter( 'ocean_blog_post_related_query_args', 'myprefix_alter_related_posts_query_args' );

All PHP snippets should be added via a child theme's functions.php file.

Did this answer your question? Thanks for the feedback There was a problem submitting your feedback. Please try again later.