Programmatic internal links: related posts by shared tags
A blog with hundreds of posts on related topics often links each post to almost nothing: readers who finish an article have no next step, and search engines see few internal connections between posts that belong together. Plugins compute “related posts” with full-text similarity, often with heavy queries. A simpler approach works well for sites with a clean taxonomy: related posts are the ones that share the most tags with the current post, computed in one query and cached.
Problem: A tutorial site with 400 posts has a related posts plugin that runs a slow LIKE query on every page view and suggests posts that only share common words. Many posts link to no other post at all.
Solution: Find the posts that share the most tags with the current one in a single SQL query, prefer older, published posts so links never point to scheduled content, cache the result per post in post meta and refresh it when tags change, and output the links at the end of the content with real anchor texts.
The query
function ha_related_ids( int $post_id, int $limit = 4 ): array {
global $wpdb;
$tag_ids = wp_get_post_terms( $post_id, 'post_tag', array( 'fields' => 'tt_ids' ) );
if ( is_wp_error( $tag_ids ) || ! $tag_ids ) {
return array();
}
$in = implode( ',', array_map( 'absint', $tag_ids ) );
return array_map( 'intval', $wpdb->get_col( $wpdb->prepare(
"SELECT tr.object_id
FROM {$wpdb->term_relationships} AS tr
JOIN {$wpdb->posts} AS p ON p.ID = tr.object_id
WHERE tr.term_taxonomy_id IN ($in)
AND tr.object_id <> %d
AND p.post_type = 'post' AND p.post_status = 'publish'
GROUP BY tr.object_id
ORDER BY COUNT(*) DESC, p.post_date DESC
LIMIT %d",
$post_id,
$limit
) ) );
}
Posts that share more tags rank higher; with the same number of shared tags, the newer post wins. The term taxonomy IDs come from WordPress and are cast to integers before they go into the IN list. Only published posts are considered, so a link can never point to a draft or a scheduled post.
Cache per post
function ha_related_cached( int $post_id ): array {
$cached = get_post_meta( $post_id, '_ha_related', true );
if ( is_array( $cached ) ) {
return $cached;
}
$ids = ha_related_ids( $post_id );
update_post_meta( $post_id, '_ha_related', $ids );
return $ids;
}
add_action( 'set_object_terms', function ( int $object_id, array $terms, array $tt_ids, string $taxonomy ): void {
if ( 'post_tag' === $taxonomy ) {
delete_post_meta( $object_id, '_ha_related' );
}
}, 10, 4 );
add_action( 'transition_post_status', function ( string $new, string $old ): void {
if ( 'publish' === $new || 'publish' === $old ) {
delete_post_meta_by_key( '_ha_related' ); // a post appeared or disappeared: recompute lazily
}
}, 10, 2 );
The list is computed once per post and stored; it is recomputed when the post’s tags change or when any post is published or unpublished. On a site with a few posts per week, a full invalidation on publish is cheap because the lists are rebuilt lazily on the next view.
Output with descriptive links
add_filter( 'the_content', function ( string $content ): string {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
$ids = ha_related_cached( get_the_ID() );
if ( ! $ids ) {
return $content;
}
$items = '';
foreach ( $ids as $id ) {
$items .= sprintf( '<li><a href="%s">%s</a></li>', esc_url( get_permalink( $id ) ), esc_html( get_the_title( $id ) ) );
}
return $content . '<nav class="ha-related" aria-label="' . esc_attr__( 'Related articles', 'textdomain' ) . '"><h2>' . esc_html__( 'Related articles', 'textdomain' ) . '</h2><ul>' . $items . '</ul></nav>';
} );
The post titles are the anchor texts, which tells readers and search engines what the linked page is about, unlike “read more”. The block is part of the server-rendered HTML, not loaded by JavaScript, so crawlers see it.
NOTE: The quality depends on the tags: two to three precise tags per post give good suggestions, twenty generic ones give random results. Links written by hand inside the text remain the strongest internal links; the list is a supplement. Finding posts that mention a phrase, as candidates for manual links: get links to posts that contain a phrase.