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 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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
How different is Handling Events in React vs HTML DOM?ReactWhen you don’t want to @forward every member in SCSS (Sass)SCSSHow to create a full screen loader using CSS and JavaScript?CSSHow to Skip or Exclude a Specific URL or File From .htaccess Rewrite Rule?PHPHow to use images instead of HTML radio buttons using CSS?CSSPostgreSQL transactions using the BEGIN, COMMIT, and ROLLBACK statements.PostgresHow to create a pricing table using flex in CSS?CSSColumn and Table Alias in PostgresPostgresWHERE Clause in PostgresPostgresContent types in DrupalDrupalSolution to “NullInjectorError: No provider for module” in Angular 9Angular6 Different Functions to Sort Arrays in PHPPHP