YogeshChauhan . com

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

amazon

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to retrieve homepage URL in WordPress?WordPressWordPress: How to get field values in Advanced Custom Fields?WordPressHow to add multiple components in React app?ReactHow to convert a number rounding to a specified number of decimals in JavaScript?JavaScriptHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPIntroduction to components and templates Part 2: Templates and viewsAngularLearn to make a responsive gallery using CSS Grid and without media queriesCSSThe Differences Between HAVING Clause and WHERE Clause in SQLSQL/MySQLWhat is iFrame in HTML? Why do we need it?HTMLThe simple difference between var, let and const in JavascriptJavaScriptSolution to “NullInjectorError: No provider for module” in Angular 9Angular5 Steps to Create a Line using Canvas Tag in HTML5HTML