'

WPX: List Similar Posts

WPX List Similar Posts is a very simple functionality plugin for WordPress that gives you a new function to display a list of posts that share the same tags or categories of the main article.

Or if you prefer you can copy and paste the function wpx_list_similar_posts into your functions.php file. For a better use, please consult the examples at the bottom of the page.

The code displays a list of titles (with permalink) that share the same Tags or Categories with the post on page, avoiding duplicated. All titles are clickable, which increases the SEO value of the page. If there aren’t other posts with the same Tags or Categories, there is no output leaving the HTML clean.

The plugin has no option page due its simplicity and does not write any values in the database. Once activated from the Plugins panel, you need to add the function into your template. Usually into the loop, just after the_content.

<?php while ( have_posts() ) : the_post(); ?>
<div class="the-post">
	<?php the_title(); ?>
	<?php the_content(); ?>
	<?php list_similar_posts(); ?>
</div>
<?php endwhile; ?>

The example above is a pure sequence of elements that compose a basic loop. Obviously a more solid theme performs a better data management, adding permalink, meta data, comments, and so on.

Installation

Download the plugin. Then extract and copy the folder wpx-list-similar-posts into the directory plugins of your installation of WordPress. At this point, from Dashboard, panel Plugin, you should be able to activate it.

Usage

The function accepts an array of four elements as argument.

  • Source
  • Number of posts to display
  • Title
  • Class
<?php // example of usage
args = array(
		'source'	=>	'categories',
		'max-posts'	=>	10,
		'title'		=>	'<h2>My title</h2>',
		'class'		=>	'my-class'
);
list_similar_posts( $args ); ?>

You can pass only the values you need to tune, say you want a different title and a list of 3 posts.

<?php args = array(
		'max-posts'	=>	3,
		'title'		=>	'<h3>My new title</h3>'
);
list_similar_posts( $args ); ?>

Let’s see few notes about the parameters you can pass to the function.

Source

You can specify if the function should recall posts inscribed in the same Tags, or in the same Categories. My choice is usually per tags.

Number of posts

By default the function shows a list of 5 posts. You can pass an other value to display as much posts as need.

Title

By default the function insert as title:

<h3>Articles on similar topics</h3>

But obviously you can pass a different line. Don’t forget to embrace the title in the appropriate tags, for instance <h3> or <h4>.

Class

You can provide a class to properly style the output. The default value is 'similar-resources'. The output is enclosed in a div.

<div class="similar-resources">
	<h3>Articles on similar topics</h3>
	<ul>
		<li><a href="#">Title of the article on topic</a></li> 
		<li><a href="#">An other article on the same topic</a></li> 
		<li>...</li>
	</ul>
</div><!-- END .similar-resources -->

The example above should give you an idea about the output, and what you may do to style it.

WPX List Similar Posts

If you prefer to copy and paste the function into your functions.php, you may want to grab the bunch of coding here below.

/*-----------------------------------------*/
/*	WPX List Similar Posts	*/
/*-----------------------------------------*/

function wpx_list_similar_posts( $args = array() ) {

	// the defaults
	$defaults = array(
		'source'	=>	'tags',
		'max-posts'	=>	5,
		'title'		=>	'<h3>Articles on similar topics</h3>',
		'class'		=>	'similar-posts'
	);
	
	// variables
	global $post;
	$posts_id_list = array();
	$query_args = array();
	$posts_lot = array();
	$rand_posts = array();
	$counter = 0;
	
	// adding the first post to the list of posts
	$posts_id_list[] = $post->ID;
	
	// parsing
	$args = wp_parse_args( $args, $defaults );

	// starting up!
	if ( $args['source'] == 'tags' ) {
		$sources = get_the_tags();
	} else if ( $args['source'] == 'categories' ) {
		$sources = get_the_category();
	} else {
		print "<!-- list_similar_posts: no valid argument found, 'from' can be only 'tags' or 'categories' -->";
		return;
	}
	
	if ( $sources ) {
		// shuffling
		shuffle( $sources );
		
		// loop through sources, and preparing the query
		foreach( $sources as $source ) {
		    
		    if ( $args['source'] == 'tags' ) {
		    	$query_args = array( 
		    		'numberposts'	=> $args['max-posts'],
		    		'orderby' 		=> 'rand',
		    		'tag'			=>	$source->name
		    	);
		    } else {
		    	$query_args = array( 
		    		'numberposts'	=> $args['max-posts'],
		    		'orderby'		=> 'rand',
		    		'category'		=>	$source->cat_ID
		    	);
		    }
		
			// getting the posts on the same topic into a randomized array
			$rand_posts = get_posts( $query_args );
			$posts_lot = array_merge( $rand_posts, $posts_lot );
			wp_reset_postdata();
		}
		
		// if we have more than the just original post on page...    
		if ( count( $posts_lot ) > 1 )	{
		    
			// print the header and open up the ul
			print '<div class="' . $args['class'] . '">' . $args['title'] . '<ul>';
				
			foreach( $posts_lot as $post_similar ) {
				if ( $counter < $args['max-posts'] && ( ! in_array( $post_similar->ID, $posts_id_list ) ) ) {
					$posts_id_list[] = $post_similar->ID; ?>
					<li><a href="<?php echo get_permalink( $post_similar->ID ); ?>"><?php echo get_the_title( $post_similar->ID ); ?></a></li> 
					<?php $counter++;
				} elseif ( $counter == $args['max-posts'] ) {
					print '</ul></div><!-- END .' . $args['class'] . ' -->';
					return;
				}
			}
			print '</ul></div><!-- END .' . $args['class'] . ' -->';
			return;
		} else {
			/* re-establish the line below if you wish to notify your readers 
			that there are no other posts on similar topics */
			// print '<div class="similar-resources">' . $args['title'] . '<p>Sorry dear reader, by far, this is the only article on the topic</p></div>';
		}
	}
} // END

Examples of usage

This section will be in progress for a while, collecting data.

First thing, it’s a safe practice to verify if a function is available before to actually call it.

if (function_exist ( 'list_similar_posts' ) ) {
	list_similar_posts();
}

This way, in case the plugin will be deactivated you do not incur in errors, or broken HTML.

Issue: no titles shown

If you don’t see any list of titles, it may be that there is no other post in the same Tags or Categories. In this case, the function avoid any output. It may also be that you did not provide a valid parameter, in fact at the moment the function accepts as valid values only 'tags' or 'categories', and not custom taxonomy.

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>