WordPress Snippets at WPcustoms

Show related posts by category

There is no need for a plugin to show related posts. This snippet takes the current posts category and lists 3 other posts from that category. Customize as required and disable your related posts plugin if you just want to list posts. It’s easy. use get_the_tags if you want to list related posts by their tags.


/**
 * Snippet Name: Show related posts by category
 * Snippet URL: http://www.wpcustoms.net/snippets/show-related-posts-by-category/
 */
 function wpc_related_posts_by_category(  ) {
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;

    $args = array(
        // It should be in the first category of our post:
        'category__in' => array( $first_cat ),
        // Our post should NOT be in the list:
        'post__not_in' => array( $post->ID ),
        'posts_per_page' => 3
    );

    $posts = get_posts( $args );
    if( $posts ) {
        $output = '
    '; foreach( $posts as $post ) { setup_postdata( $post ); $post_title = get_the_title(); $permalink = get_permalink(); $output .= '
  • ' . $post_title . '
  • '; } $output .= '
'; } else { $output .= '

Sorry, no other posts matched this category.

'; } echo $output; }