<div class="related-posts comm-title">
<h3 class="widgettitle"><span><?php esc_html_e( 'Related Posts', 'liberis' ); ?></span></h3>

<?php 

$categories = get_the_category($post->ID);

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'=> 3, // Number of related posts that will be shown.
'ignore_sticky_posts'=>true,
'orderby'=>'rand'
);

}

else {

 $args=array(
'post__not_in' => array($post->ID),
'posts_per_page'=> 3, // Number of related posts that will be shown.
'ignore_sticky_posts'=>true,
'orderby'=>'rand'
); 

}
	$single_query = new WP_Query($args);
	
?>

<ul class="related-posts-holder">
        
<?php if ( $single_query -> have_posts()) : while ( $single_query -> have_posts()) : $single_query -> the_post(); ?>

<li>

<div class="related-img">

<a href="<?php the_permalink();?>">

<?php if ( has_post_thumbnail($post->ID ) ): ?>

<?php the_post_thumbnail('liberis-image700x400', array('class'=> 'img-fluid', 'alt' => ''.get_the_title().'', 'title' => ''.get_the_title().'')); ?>

<?php else: ?>

<img class="img-fluid" src="<?php echo get_template_directory_uri() . '/images/default-img.png'?>" alt="<?php esc_html_e('Default image','liberis'); ?>"/>

<?php endif; ?>
 
</a>
      
</div>

<div class="related-date"><?php echo get_the_date(get_option('date_format')); ?></div>
           
<h4 class="related-title"><a href="<?php the_permalink();?>"><?php echo the_title(); ?></a></h4>

</li>	
	
<?php endwhile; 

wp_reset_postdata();

?> 

</ul>

<?php else: ?>

<p class="alignc"><?php esc_html_e( 'Sorry, but it seems we can&rsquo;t find what you&rsquo;re looking for. Try the menu above.', 'liberis' ); ?></p>

<?php endif; ?>

</div>