• Do not post forums in any language other than English. Moreover, political, religious and adult content cannot be posted. Requested not to spamming posts. Such posts will be deleted very soon.

Query for WordPress Related Posts without plugin.

admin

Administrator
Staff member
Many people are trying to wordpress theme developent. Sometimes they are looking, How to add add related post into wordpress without any plugin?

Now I will share the simple code to add Realated post inside/ bottom / sidebar of the post page. How have just nothing to extra coding for configure it. Just go to your single.php file or which file it show single post, Just add below code and test now.
Code:
<?php
  $catArgs = array(
    'category__in' => wp_get_post_categories($post->ID), //No need to change ID
    'showposts' => 2, //display number of posts
    'orderby' =>'popular', //display popular posts, rand for random posts
    'post__not_in' => array($post->ID) //No need to change ID
  );
$cat_post_query = new WP_Query($catArgs);
  if( $cat_post_query->have_posts() ) {
?>
<div class="related_posts">
  <h3>You may also like</h3>
    <?php while ($cat_post_query->have_posts()){
        $cat_post_query->the_post(); ?>
        <div class="related_itemspl">
          <div class="related_thumb">
          <a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"> <?php the_post_thumbnail( 'small-thumbnail'); ?> <?php the_title(); ?></a>
          </div>
        </div>
    <?php } ?>
</div>
<?php wp_reset_query(); } ?>

You can use below code, If you use custom type of post. For example here is post type email.
Code:
<?php
  $catArgs = array(
    'post_type' => 'email', //Post type
    'showposts' => 3, //Number of post
    'orderby' =>'popular', //Popular Post
    'post__not_in' => array(get_the_ID()) //Remove some post from list
  );
$cat_post_query = new WP_Query($catArgs);
  if( $cat_post_query->have_posts() ) {
?>
<div>
  <!-- <?php echo get_the_ID(); ?> -->
  <h4>You may also like</h4>
    <?php while ($cat_post_query->have_posts()){
        $cat_post_query->the_post(); ?>
        <p><?php echo the_title(); ?></p>
    <?php } ?>
</div>
<?php wp_reset_query(); } ?>

Please don't feel hasitate to comment here, if you faced any problem.
 
Last edited:
Top