Yogesh Chauhan's Blog

How to Display Related Posts in WordPress?

in WordPress on October 15, 2020

Here is the code we can use to display related posts.



<?php

//for use in the loop, list 5 post titles related to first tag on current post

$tags = wp_get_post_tags($post->ID);

if ($tags) {

  echo 'Related Posts';

  $first_tag = $tags[0] -> term_id;

  $args = array (

    'tag__in' => array($first_tag),

    'post__not_in' => array($post->ID),

    'showposts'=>5,

    'caller_get_posts'=>1

   );

  $my_query = new WP_Query($args);

  if( $my_query->have_posts() ) {

    while ($my_query->have_posts()) : $my_query->the_post(); 

?>

<p>

   <a href="<?php the_permalink() ?>" 
      rel="bookmark"
      title="Permanent Link to <?php the_title_attribute(); ?>">
      <?php the_title(); ?>
   </a>

</p>

<?php

    endwhile;
  
  }

}

?>

Credit: WP Support


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
2 Ways we can create an Array in JavaScriptJavaScriptControl Scrolling with CSS Scroll SnapCSSHow to use PHPMailer to send an Email via Gmail SMTP Server?PHPSolution to Precision Problem in JavaScript NumbersJavaScriptHow to modify AutoSave Interval using code in WordPress?WordPressHow different is Handling Events in React vs HTML DOM?ReactHow to add AppRoutingModule in Angular application using command line?AngularHow to get Current Hour, Minute and Second in JavaScript?JavaScriptWindow setInterval() Method in JavaScriptJavaScriptIntroduction to components and templates Part 2: Templates and viewsAngularWhat is the difference between let and var in Swift?SwiftLearn to Establish Connection using MySQLi (object-oriented), MySQLi (procedural) and PDO with Example CodePHP