YogeshChauhan.com
How to Display Related Posts in WordPress?
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

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

Introduction to components and templates Part 2: Templates and viewsAngularHow to show widgets on the Appearance tab in WordPress?WordPressHow to center an image horizontally and vertically?CSSHow To Create a Fullscreen Background Video using CSS and JavaScript?CSSSolution to “TypeError: ‘x’ is not iterable” in Angular 9AngularWhat Is a Graph Database?MiscHow to get start index and end index (as int) of substring in Swift?SwiftHow to create Glowing Text using CSS?CSSHow to obfuscate JavaScript code to hide it from View Source?JavaScriptImplicit and Explicit Joins in Oracle SQLSQL/MySQLHow to remove a specific item from an array in JavaScript?JavaScript3 JavaScript methods to use when you want to go back and forth in historyJavaScript