Related Post Link in the Middle of Articles
Places a "Related" link to another post from the same category halfway through each blog post, a well-placed internal link that keeps readers on the site.
Opens WPIDE on
Code
$wpide_mid_post_id = get_the_ID();
if ( ! $wpide_mid_post_id || 'post' !== get_post_type( $wpide_mid_post_id ) ) {
return;
}
$wpide_mid_related = get_transient( 'wpide_mid_related_' . $wpide_mid_post_id );
if ( false === $wpide_mid_related ) {
$wpide_mid_ids = get_posts( array(
'category__in' => wp_get_post_categories( $wpide_mid_post_id ),
'post__not_in' => array( $wpide_mid_post_id ),
'posts_per_page' => 1,
'ignore_sticky_posts' => true,
'fields' => 'ids',
'no_found_rows' => true,
) );
$wpide_mid_related = $wpide_mid_ids ? (int) $wpide_mid_ids[0] : 0;
set_transient( 'wpide_mid_related_' . $wpide_mid_post_id, $wpide_mid_related, WEEK_IN_SECONDS );
}
if ( $wpide_mid_related && 'publish' === get_post_status( $wpide_mid_related ) ) {
printf(
'<aside class="mid-article-related" style="margin:1.5em 0;padding:.75em 1em;border-left:4px solid currentColor"><strong>Related:</strong> <a href="%1$s">%2$s</a></aside>',
esc_url( get_permalink( $wpide_mid_related ) ),
esc_html( get_the_title( $wpide_mid_related ) )
);
}
Notes
Inserted at the middle of the content by the snippet location. The related post is chosen once per post and cached for a week.
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.