Related Posts Below Single Posts
Lists three posts from the same categories at the end of each single post. No plugin, no extra database tables.
Opens WPIDE on
Code
add_filter( 'the_content', function ( $content ) {
if ( ! is_singular( 'post' ) || ! in_the_loop() || ! is_main_query() ) {
return $content;
}
$post_id = get_the_ID();
$categories = wp_get_post_categories( $post_id );
if ( ! $categories ) {
return $content;
}
$related = get_posts( array(
'category__in' => $categories,
'post__not_in' => array( $post_id ),
'numberposts' => 3,
'ignore_sticky_posts' => true,
'no_found_rows' => true,
) );
if ( ! $related ) {
return $content;
}
$html = '<aside class="wpide-related-posts"><h3>Related posts</h3><ul>';
foreach ( $related as $item ) {
$html .= '<li><a href="' . esc_url( get_permalink( $item ) ) . '">' . esc_html( get_the_title( $item ) ) . '</a></li>';
}
return $content . $html . '</ul></aside>';
}, 20 );
Notes
Change numberposts to show more or fewer posts.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.