lmartins
12/3/2014 - 11:33 PM

get-related-posts.php

<?php
/**
 * Display Related Posts
 */
function child_do_related_posts() {

	$related = child_get_related_posts( get_the_id() );

	if ( $related->have_posts() ) : ?>

		<div class="related-posts">
			<h4 class="related-posts-title"><?php _e( 'Related Posts', 'child' ); ?></h4>
			<ul class="related">

			<?php $count = 1 ?>
			<?php while ( $related->have_posts() ) : $related->the_post(); ?>

				<li class="related-post related-<?php echo $count; ?>">
					<a href="<?php echo esc_url( get_permalink() ); ?>"><img src="<?php echo esc_url( nps_get_post_thumbnail_uri() ); ?>" class="related-image wp-post-image" height="190" width="190" alt="<?php echo esc_html( get_the_title() ); ?>" title="<?php echo esc_html( get_the_title() ); ?>" /></a>
					<a class="related-url" href="<?php echo esc_url( get_permalink() ); ?>"><?php echo esc_html( get_the_title() ); ?></a>
				</li>

			<?php $count++ ?>
			<?php endwhile; ?>

			</ul>
		</div>

		<?php else : ?>

			<?php _( 'Sorry. No related posts were found.', 'child' ); ?>

	<?php endif; ?>
	<?php wp_reset_postdata(); ?>
<?php
}
<?php
/**
 * Get related posts for a given post ID.
 *
 * @param  integer $post_id Post ID.
 * @param  integer $count   Number of posts to fetch.
 * @return array            Post objects.
 */
function child_get_related_posts( $post_id ) {

	if ( false === ( $related = get_transient( 'child_related_posts_' . $post_id ) ) ) {

		$cats = wp_get_post_categories( absint( $post_id ) );

		$related = new WP_Query( array(
			'category__in'        => array_shift( $cats ),
			'post__not_in'        => array( $post_id ),
			'posts_per_page'      => 4,
			'ignore_sticky_posts' => 1
		) );

		set_transient( 'child_related_posts_' . $post_id, $related, 12 * HOUR_IN_SECONDS );

	}

	return $related;
}