Category: WordPress

Creating a WordPress ‘Recent Posts’ Area That Has The Same Categories As the Current Post

test

For anyone needing to create a Recent Posts area that filters the recent posts based on the category of your current post using WordPress. Copy the code below into your functions.php. In this example the code produces a 3 columns which display the post thumbnail and title. I am using the Foundation framework but it would work the same with Bootstrap or any other just modify the div syntax.

function current_related_posts() {
 
    $post_id = get_the_ID();
    $cat_ids = array();
    $categories = get_the_category( $post_id );
 
    if ( $categories && !is_wp_error( $categories ) ) {
 
        foreach ( $categories as $category ) {
 
            array_push( $cat_ids, $category->term_id );
 
        }
 
    }
    $current_post_type = get_post_type( $post_id );
         
    $args = array(
        'category__in' => $cat_ids,
        'post_type' => $current_post_type,
        'posts_per_page' => '3',
        'post__not_in' => array( $post_id )
    );
    $query = new WP_Query( $args );
     
    if ( $query->have_posts() ) {
     
    ?>
        <h3>
            <?php _e( 'Related Posts'); ?>
        </h3>
            <?php

            while ( $query->have_posts() ) {

            $query->the_post();

            ?>
            <?php echo '<div class="small-12 medium-6 large-4 columns">'; ?>
            <a href="<?php echo get_permalink() ?>">
                <?php if ( has_post_thumbnail() ) : ?>
                    <?php the_post_thumbnail('large') ?>
                <?php endif ?>
            </a>
            <a class="title" href="<?php echo get_permalink() ?>"><?php the_title() ?></a>
            <?php echo '</div>'; ?>
            <?php

            }
 
            ?>
    <?php
     
    }
     
    wp_reset_postdata();
 
}

 

Then copy the function into your theme file where you would like it to appear.

<?php current_related_posts(); ?>