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 How to check if radio button is checked or not using JavaScript? #2 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #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
What’s a Log File and What are Log File Monitors?MiscellaneousAggregate Functions Examples in Postgres for BeginnersPostgresHow does while loop work in SCSS?SCSSLIMIT and OFFSET in PostgresPostgresHow to remove border from :visited image, link or button?CSSHow to create two segues with two UIButtons on a single page (Swift 5.0)?SwiftHow to set up the local environment and workspace for Angular development?AngularHow to insert Bootstrap 4 in Angular 9 app?AngularWordPress: How to query all posts from custom post type and display them in a list?WordPressRendering Elements in ReactReactHow to add transparent text on top of an image using CSS?CSSWindow setInterval() Method in JavaScriptJavaScript