Add related posts to wordpress easily and without plugin, related posts shortcode and add related posts after posts content automatically.

How To Add Related Posts

We will learn how to add related posts in wordpress easily and without plugin, usingĀ wp_get_post_tags() function andĀ get_posts() function we will make related posts function, and using Shortcode API we will make related posts shortcode.

Related Posts Function

Now we make related posts function:

function WPTime_related_posts(){
    /* function by Qassim Hassan - http://wp-time.com */

    if( !is_single() ){ // if not single post:
        return false; // do not showing function!.
    }

    global $post;
    $get_tags = wp_get_post_tags($post->ID); // get post tags
    $tag_ids = array(); // make array

    if( !$get_tags ){ // if not found post tags:
        return false; // do not showing function!.
    }

    if( $get_tags ){

        foreach( $get_tags as $get_tag ){
            $tag_ids[] = $get_tag->term_id; // add post tags to our array.
        }

    }

     $args = array(
        'numberposts' => 5, // number of related posts, change it if you want.
        'tag__in' => $tag_ids, // get tag IDs.
        'post__not_in' => array( $post->ID ), // ignore current post, you can change it if you want.
        'post_status' => 'publish' // only published posts, you can change it if you want.
    );

    $related_posts = get_posts($args);

    if( !$related_posts ){ // if not found related posts:
        return false; // do not showing function!.
    }

    $get_list = '';

    foreach( $related_posts as $related_post ){
        $get_list .= '<li><a href="'.esc_url( get_permalink($related_post->ID) ).'" title="'.get_the_title($related_post->ID).'">'.get_the_title($related_post->ID).'</a></li>'; // list of related posts.
    }

    echo "<h4>Related Posts</h4>";
    echo "<ul>";
    echo $get_list;
    echo "</ul>";
}

Related Posts Shortcode

Now we make related posts shortcode:

function my_related_posts_shortcode(){
    // use this shortcode [my_related_posts] in your posts or widget if you want.
    ob_start();
    WPTime_related_posts(); // our related posts function.
    return ob_get_clean();
}
add_shortcode('my_related_posts', 'my_related_posts_shortcode');

Now this is our related posts shortcode “[my_related_posts]” you can using it in your posts or in text widget.

Add Related Posts After Content Automatically

Now using the_content filter we will add related posts after posts content automatically:

function add_related_posts_after_content( $content ){
    return $content.do_shortcode('[my_related_posts]');
}
add_filter('the_content', 'add_related_posts_after_content', 999);

Related Posts Plugin

You can using The Related Posts plugin, easy to use, just activate it.