Related posts (wordpress)

Get related posts from a category or tag.

<?php
    // Related posts (categories)
    $categories = get_the_category($post->ID);
    if ($categories) {
        $category_ids = array();
        foreach ($categories as $individual_category) {
            $category_ids[] = $individual_category->term_id;
        }
        $q = new WP_Query(array(
            'category__in' => $category_ids,
            'post__not_in' => array($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();
        }
    }
?>

<?php
    // Related posts (tags)
    $tags = wp_get_post_tags($post->ID);
    if ($tags) {
        $tag_ids = array();
        foreach($tags as $individual_tag) {
            $tag_ids[] = $individual_tag->term_id;
        }
        $q = new WP_Query(array(
            'tag__in' => $tag_ids,
            'post__not_in' => array($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

< toolbox