December 30, 2024
1 min read

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

single.php
<?php
/**
 * Related post code
 *
 * code from https://www.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(
        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() ) : ?>
<ul>
    <?php while ( $query->have_posts() ) : $query->the_post(); ?>
    <li> <a href="<?php the_permalink(); ?>"><?php the_title() ?>
        </a></li>
    <?php endwhile; ?>
</ul>
<?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.

Leave a Reply

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

Change WordPress URL in Database with phpMyAdmin and SQL query

Replace WordPress old URL to new URL with SQL Query

Create a new WordPress administrator via functions.php & FTP

Sometimes, you might need to create an administrator account in WordPress without being able to access the admin dashboard. This could be because you have lost access to your site’s admin panel or when troubleshooting a client’s website. In this tutorial, we will show you how to programmatically add a WordPress administrator account using the […]

Enabling Guest Checkout in WooCommerce: Bypassing Email Verification for Order Payment

Enable guest payment, bypass email verification. Enhance user experience, boost conversions. Easy, efficient, and customer-friendly solution

Enable Leverage browser caching & Compression

To speed up your website and get good score, Enable Leverage browser caching & Compression

Web Development Project in mind?

if you looking for a web developer for paid contribution to your project I am available for work.

Mukto
Mukto

Click the button below to chat with me.