<?php
/**
 * Template for showing related posts.
 * Display affected by customizer option to show/hide and the number of posts
 *
 * @package pixigo
 */

$categories         = get_the_category( $post->ID );
$related_post_count = get_theme_mod( 'pixigo_related_post_count', 2 );

// To avoid negative related post count.
$related_post_count = ( $related_post_count > 0 ) ? $related_post_count : 2;

if ( $categories ) :

	$category_ids = array();

	foreach ( $categories as $individual_category ) {
		$category_ids[] = $individual_category->term_id;
	}

	$args = array(
		'category__in'        => $category_ids,
		'post__not_in'        => array( $post->ID ),
		'posts_per_page'      => $related_post_count,
		'ignore_sticky_posts' => 1,
	);

	$related_posts_query = new WP_Query( $args );

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

		<div class="related-posts">
			<h4><?php echo esc_html( get_theme_mod( 'pixigo_related_post_text', 'Related Posts' ) ); ?></h4>

			<div class="related-posts-grid">

					<?php
					while ( $related_posts_query->have_posts() ) :
						$related_posts_query->the_post();
						?>

						<article id="post-<?php the_ID(); ?>" <?php post_class( 'card' ); ?>>

							<div class="entry-meta">
								<div class="cat-links"><?php pixigo_post_categories(); ?></div>
								<div class="post-meta">
									<?php pixigo_posted_on(); ?>
								</div>
							</div><!-- .entry-meta -->

							<header class="entry-header">
								<?php the_title( '<h4 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h4>' ); ?>
							</header><!-- .entry-header -->

						</article><!-- #post-<?php the_ID(); ?> -->

					<?php endwhile; ?>

			</div> <!-- .related-posts-grid -->
		</div>

		<?php
	endif;
endif;

wp_reset_postdata();
