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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
Solution for “Yarn build: Failed because of a stylelint error”WordPressHow to Skip or Exclude a Specific URL or File From .htaccess Rewrite Rule?PHPHow to add MySQL alternate port and sockets/pipes in WordPress?WordPressHow to remove trailing characters from a string using JavaScript?JavaScriptHow to link/add CSS file to HTML Document?CSSThe basics of @import rule in SCSS (Sass)SCSSIntroduction to components and templates Part 3: Data bindingAngularHow to delete a local and a remote Git branches?MiscellaneousWhat is Hoisting in JavaScript?JavaScriptHow to pass arguments in SCSS function?SCSS2 Ways We Can Write Multiple Line Commands in PHPPHPAdd animated hamburgers menu using Hamburgers collection on GitHubCSS