Content & Posts PHP Intermediate

Related Posts by Category Without a Plugin

Query and return related posts from the same category as the current post, with a simple caching layer to avoid repeat database queries on popular posts.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 48 lines
/**
 * Get related posts from the same primary category.
 *
 * Usage in single.php or a template part:
 *   $related = nahnu_get_related_posts();
 *   foreach ( $related as $post ) {
 *       setup_postdata( $post );
 *       // Use standard template tags: the_title(), the_permalink(), etc.
 *   }
 *   wp_reset_postdata();
 *
 * @param int $count     Number of posts to return. Default 3.
 * @param int $post_id   Post to find relations for. Default current post.
 * @return WP_Post[]
 */
function nahnu_get_related_posts( int $count = 3, int $post_id = 0 ): array {
    if ( ! $post_id ) $post_id = get_the_ID();

    $cache_key = 'nahnu_related_' . $post_id . '_' . $count;
    $cached    = wp_cache_get( $cache_key );
    if ( $cached !== false ) return $cached;

    $terms = get_the_terms( $post_id, 'category' );
    if ( ! $terms || is_wp_error( $terms ) ) return [];

    $term_ids = wp_list_pluck( $terms, 'term_id' );

    $related = get_posts( [
        'post_type'           => get_post_type( $post_id ),
        'posts_per_page'      => $count,
        'post__not_in'        => [ $post_id ],
        'post_status'         => 'publish',
        'orderby'             => 'rand',
        'tax_query'           => [
            [
                'taxonomy' => 'category',
                'field'    => 'term_id',
                'terms'    => $term_ids,
            ],
        ],
        'no_found_rows'       => true,  // Skip COUNT(*) for performance
        'ignore_sticky_posts' => true,
    ] );

    wp_cache_set( $cache_key, $related, '', 3600 ); // Cache for 1 hour

    return $related;
}

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

Related posts are one of the most effective ways to reduce bounce rate and increase pages-per-session, showing a reader who just finished an article three more pieces of content on the same topic gives them a clear next step. Most related posts implementations use a plugin that adds database overhead, JavaScript, and often external API calls. This snippet gives you a clean, cacheable function that queries the database directly and returns a standard array of WP_Post objects you can render with any template code.

What the code does

The function is standalone, it doesn’t output anything on its own. Call it in your single post template and loop through the returned posts using standard WordPress template tags.

How to Use It

In single.php or a dedicated related posts template part, call nahnu_get_related_posts() and loop through the result. After the loop, call wp_reset_postdata() to restore the global post state. The function returns an empty array when no related posts exist, so the loop is safely skipped. Pass a count as the first argument, nahnu_get_related_posts( 4 ) for four related posts, for example.

The Query

The function finds the current post’s categories using get_the_terms(), extracts the term IDs, and runs a get_posts() query filtered by those category IDs. post__not_in excludes the current post from the results. orderby = rand randomises the selection so returning visitors don’t always see the same three posts, though note that rand ordering prevents MySQL query caching, which is partly why the object cache layer is included.

no_found_rows => true skips the SQL COUNT(*) query that WordPress normally runs alongside the main query to calculate pagination totals. Since related posts don’t need pagination, this is a useful performance saving on every call.

The Caching Layer

Results are stored in WordPress’s object cache using wp_cache_set() with a one-hour expiry. The cache key includes both the post ID and the requested count, so requesting 3 and 4 related posts for the same post produces separate cache entries. On sites with a persistent object cache, Memcached, Redis, this eliminates the database query entirely for cached results. On sites without a persistent cache, the cache is request-scoped and helps avoid repeat queries within the same page load.

Adapting for Custom Taxonomies

For custom post types using a custom taxonomy, replace 'category' in both get_the_terms() and the tax_query with your taxonomy slug. The function structure is the same, only the taxonomy identifier changes.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only