WordPress Related Post | Code For Developers

WordPress Related Post

Show related post on blog single page or any custom post single page

We are going to show some related posts on the blog single page. Here the trick is very simple. We are going to show post from the same category (you can use tag also) and we will make the post appear randomly so it looks like the same as the related post. Also, we will hide the current post that we are reading from the related post. let do it with the simple code.

You need to put this code on sidebar or bottom of main post at single.php or your custom post type single php

 * Related post code
 * code from https://code.mukto.info
 * You can use same code for custom post type and taxomoy as well
//get the taxonomy terms of custom post type
$customTaxonomyTerms = wp_get_object_terms( $post->ID, 'category', array('fields' => 'ids') );

//query arguments
$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page' => 5,
    //show random posts
    'orderby' => 'rand',
    'tax_query' => array(
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $customTaxonomyTerms
    //hide current post from the list
    'post__not_in' => array ($post->ID),
$query = new WP_Query( $args );


<?php if( $query->have_posts() ) : ?>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
    <li> <a href="<?php the_permalink(); ?>"><?php the_title() ?>
    <?php endwhile; ?>
<?php endif; ?>

<?php wp_reset_query(); ?>

Wohoo we are done with simple code. You can customize html to give your desire look. Make sure you have more then 1 post on that taxonomy.

Previous Code

WordPress category or taxonomy list

WordPress custom taxonomy term list with function ...

Next Code

JQuery Auto Hight

jQuery height change after a specific time interva ...

Leave a Reply

Your email address will not be published. Required fields are marked *

If you find it useful

Buy me a coffee









Most View or Popular Post on WordPress

WordPress Post query by user views without plugin ...

Conditional statement to show pagination

Conditional statement to show pagination on WordPr ...

WordPress Ajax Search without plugin [ Easy ]

WordPress Ajax Search without plugin. Fully custom ...

WordPress Next and Previous Post

WordPress Next and Previous Post navigation for cu ...

WP Post Query with variable item column size