<?php
if ( ! function_exists( 'hardware_dealer_pro_related_posts_function' ) ) {
	function hardware_dealer_pro_related_posts_function() {
		wp_reset_postdata();
		global $post;

		// Define shared post arguments
		$args = array(
			'no_found_rows'          => true,
			'update_post_meta_cache' => false,
			'update_post_term_cache' => false,
			'ignore_sticky_posts'    => 1,
			'orderby'                => 'rand',
			'post__not_in'           => array( $post->ID ),
			'posts_per_page'         => '3',
		);
		// Related by categories
		if ( 'categories'  == 'categories' ) {

			$cats = get_post_meta( $post->ID, 'related-posts', true );

			if ( ! $cats ) {
				$cats                 = wp_get_post_categories( $post->ID, array( 'fields' => 'ids' ) );
				$args['category__in'] = $cats;
			} else {
				$args['cat'] = $cats;
			}
		}
		// Related by tags
		if ( 'categories' == 'tags' ) {

			$tags = get_post_meta( $post->ID, 'related-posts', true );

			if ( ! $tags ) {
				$tags            = wp_get_post_tags( $post->ID, array( 'fields' => 'ids' ) );
				$args['tag__in'] = $tags;
			} else {
				$args['tag_slug__in'] = explode( ',', $tags );
			}
			if ( ! $tags ) {
				$break = true;
			}
		}

		$query = ! isset( $break ) ? new WP_Query( $args ) : new WP_Query();

		return $query;
	}
}

$related_posts = hardware_dealer_pro_related_posts_function(); ?>

<?php if ( $related_posts->have_posts() ): ?>

	<div class="related-posts clearfix">
			<h2 class="related-posts-main-title">
        <?php echo esc_html(__('Related Posts','hardware-dealer-pro') ); ?>
      </h2>
		<div class="related-post-container">
			<?php while ( $related_posts->have_posts() ) : $related_posts->the_post(); ?>
				<div class="related-post-box">
					<div class="postbox">
				    	<div class="post-featured">
					        <?php if ( has_post_thumbnail() ) { the_post_thumbnail(); } ?>
					        <div class="inner-sbox align-items-center">
					          	<h3 class="related-post-title">
					            	<a href="<?php the_permalink();?>">
													<?php the_title();?>
												</a>
					          	</h3>
					          	<p>
					            	<?php
					              	$excerpt = get_the_excerpt();
													if (strlen($excerpt) > 150){
														$excerpt = substr($excerpt, 0, 150) . '...';
														echo $excerpt;
													}else {
														echo $excerpt;
													}
					            	?>
					          	</p>
					          	<a href="<?php the_permalink();?>" class="post-readmore"><?php _e('Read Full', 'hardware-dealer-pro')?>
												<i class="fas fa-long-arrow-alt-right"></i>
											</a>
					        </div>
				      	</div>
				    </div>
				</div>
			<?php endwhile; ?>
		</div>

	</div><!--/.post-related-->
<?php endif; ?>

<?php wp_reset_postdata(); ?>
