WordPress: Display Related Posts by Category

- Advertisement -

If you’re looking to display related posts on your WordPress website, there are a few different ways to do it. In this article, we’ll cover two methods: using custom code in your theme, and using a plugin.

Method 1: Custom Code

- Advertisement -

If you want to display related posts without using a plugin, you can do so by adding some custom code to your theme. Here’s how:

1. Open your theme’s functions.php file.

- Advertisement -

2. Paste the following code at the end of the file:

“`

- Advertisement -

// Default arguments

$args = array(

‘posts_per_page’ => 4, // How many items to display

‘post__not_in’ => array( get_the_ID() ), // Exclude current post

‘no_found_rows’ => true, // We don’t need pagination so this speeds up the query

);

// Check for current post category and add tax_query to the query arguments

$cats = wp_get_post_terms( get_the_ID(), ‘category’ );

$cats_ids = array();

foreach( $cats as $wpex_related_cat ) {

$cats_ids[] = $wpex_related_cat->term_id;

}

if ( ! empty( $cats_ids ) ) {

$args[‘category__in’] = $cats_ids;

}

// Query posts

$wpex_query = new wp_query( $args );

// Loop through posts

foreach( $wpex_query->posts as $post ) : setup_postdata( $post ); ?>

- Advertisement -

Stay in Touch

spot_img

Related Articles