Get related posts from a category or tag.
<?php
$related_shown = false;
// Related posts (categories)
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = [];
foreach ($categories as $individual_category) {
$category_ids[] = $individual_category->term_id;
}
$q = new WP_Query([
'category__in' => $category_ids,
'post__not_in' => [$post->ID],
'posts_per_page'=> 5,
'ignore_sticky_posts'=> 1,
]);
if ($q->have_posts()) {
echo '<h3>Related Posts</h3>';
echo '<ul>';
while ($q->have_posts()) {
$q->the_post();
printf(
'<li><a href="%s">%s</a></li>',
esc_url(get_permalink()),
esc_html(get_the_title()),
);
}
echo '</ul>';
$related_shown = true;
}
wp_reset_postdata();
}
// Related posts (tags)
if (!$related_shown && ($tags = get_the_tags($post->ID))) {
$tag_ids = [];
foreach($tags as $individual_tag) {
$tag_ids[] = $individual_tag->term_id;
}
$q = new WP_Query([
'tag__in' => $tag_ids,
'post__not_in' => [$post->ID],
'posts_per_page'=> 5,
'ignore_sticky_posts'=> 1,
]);
if ($q->have_posts()) {
echo '<h3>Related Posts</h3>';
echo '<ul>';
while ($q->have_posts()) {
$q->the_post();
printf(
'<li><a href="%s">%s</a></li>',
esc_url(get_permalink()),
esc_html(get_the_title()),
);
}
echo '</ul>';
}
wp_reset_postdata();
}
?>
template.php