Wordpress Related Post

PHOTO EMBED

Mon Feb 12 2024 07:55:29 GMT+0000 (Coordinated Universal Time)

Saved by @suira #php #wordpress

if ( is_single() ) {
  $current_post_id = get_queried_object_id();
  $current_category_id = get_the_category( $current_post_id )[0]->cat_ID;

  $args = array(
    'category' => $current_category_id,
    'post__not_in' => array( $current_post_id ),
    'posts_per_page' => 3,
  );

  $related_posts = new WP_Query( $args );

  if ( $related_posts->have_posts() ) {
    echo '<h2>Related Posts:</h2>';
    while ( $related_posts->have_posts() ) {
      $related_posts->the_post();
      echo '<a href="' . get_the_permalink() . '">' . get_the_title() . '</a><br>';
    }
    wp_reset_postdata();
  }
}
content_copyCOPY

Show related posts in Wordpress single.php