How To Add Related Posts To Your Theme?

To add related posts to your theme, open functions.php file and add the following code.

function hs_related_posts()
{
    $categories = get_the_category();
    if (count($categories) > 0) :
        ?>

        <?php
        $terms = get_the_terms(get_the_ID(), 'category');

        if (empty($terms)) $terms = array();

        $term_list = wp_list_pluck($terms, 'slug');

        $related_args = array(
            'post_type' => 'post',
            'posts_per_page' => 3,
            'post_status' => 'publish',
            'post__not_in' => array(get_the_ID()),
            'tax_query' => array(
                array(
                    'taxonomy' => 'category',
                    'field' => 'slug',
                    'terms' => $term_list
                )
            )
        );

        $the_query = new WP_Query($related_args);
        global $cl_from_element;
        $cl_from_element['is_related'] = true;
        // Display posts
        if ($the_query->have_posts()) :
        ?>
            <div class="related-posts">
                <h2 class="widget-title">
                    <?php esc_html_e('Related Posts', 'text-domain') ?>
                </h2>
                <div class="posts">
                    <?php $counter = 1;
                    while ($the_query->have_posts() && $counter < 4) :
                        $the_query->the_post(); ?>
                        <div class="related-post">

                            <a href="<?php echo esc_url(get_permalink()); ?>">
                                <?php if (has_post_thumbnail()) : ?>
                                    <div class="related-post-thumbnail">
                                        <?php the_post_thumbnail(); ?>
                                    </div>
                                <?php endif; ?>
                            </a>

                            <?php the_title(sprintf('<h2 class="related-post-title"><a href="%s" rel="bookmark">', esc_url(get_permalink())), '</a></h2>'); ?>

                        </div>
                    <?php
                        $counter++;
                    endwhile;
                    ?>
                </div>
            </div>
            <?php endif;

        wp_reset_query();
        $cl_from_element['is_related'] = false;
    endif;
}

Go to your posts display loop and add the function in it.

hs_related_posts();
Shopping Cart