<?php
/**
 * @version    $Id$
 * @package    IT_Theme_Framework
 * @author     InnoThemes Team <support@innothemes.com>
 * @copyright  Copyright (C) 2012 InnoThemes.com. All Rights Reserved.
 * @license    GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 *
 * Websites: http://www.innothemes.com
 */

// Get post's tags
$tags = wp_get_post_tags( $post->ID );

if ( $tags ) {
	// Get id for all tags
	$tag_ids = array();

	foreach ( $tags as $tag ) {
		$tag_ids[] = $tag->term_id;
	}

	// Build arguments to query for related posts
	$args = array(
		'tag__in'          => $tag_ids,
		'post__not_in'     => array( $post->ID ),
		'posts_per_page'   => 5,
		'caller_get_posts' => 1,
		'orderby'          => 'rand',
	);

	// Get related post
	$related = new wp_query( $args );

	if ( $related->have_posts() ) {
		// Filter HTML code for related posts list
		$wrapper = apply_filters( 'it_theme_related_posts_wrapper', '<div id="related-posts"><h3>%1$s</h3><ul>%2$s</ul></div>' );
		$loop    = apply_filters( 'it_theme_related_posts_loop'   , '<li><a href="%1$s">%2$s</a></li>'                         );

		$list_items = '';

		while ( $related->have_posts() ) {
			// Update global post data
			$related->the_post();

			$list_items .= sprintf( $loop, get_permalink(), get_the_title() );
		}

		// Print related posts list
		printf( $wrapper, __( 'Related Posts', IT_THEME_TEXTDOMAIN ), $list_items );
	}

	// Reset global query object
	wp_reset_postdata();
}
