Related post in the same category

Marko Krstić
18 Jan 2020

This is custom code will loop 3 posts in same categories without a current post with random sorting.

<?php
$args = array(
                'category__in' => wp_get_post_categories( get_queried_object_id() ),
                'posts_per_page' => 3,
                'orderby'       => 'rand',
                'post__not_in' => array( get_queried_object_id() )
                );
    $the_query = new WP_Query( $args );
    if ( $the_query->have_posts() ) : ?>
        <ul class="">
        <!-- the loop -->
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
            <li>
                <h6>
                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                    <?php the_title(); ?>
                    </a>
                </h6>
            </li>
        <?php endwhile; ?>
        <!-- end of the loop -->
        </ul>
        <?php wp_reset_postdata(); ?>
     <?php endif; ?>

Was this article helpful?

Tags

Categories

Never miss new post again

Subscribe and get list of new posts in your inbox

Click to Copy