0

How to display related posts according to Title and Category on a WordPress single page?

Here is my code:

<?php 
$args = array(                          
    'category__in'   => $cat_id, // OK
    'posts_per_page' => 6,
    'post__not_in'   => array( get_the_ID() ),
);
                    
$wpex_query = new WP_Query( $args );
?>

Note: Using category in query is OK. But I also want the Title in the query.

1 Answer 1

1

Probably the simplest approach is to combine the category query with a search query (untested):

$cat_query = new WP_Query( array(
    'cat'            => $cat_id,
    'post__not_in'   => array( get_the_ID() ),
    'no_found_rows'  => false,
    'posts_per_page' => 6,
) );

$title_query = new WP_Query( array(
    'post__not_in'   => array( get_the_ID() ),
    's'              => get_the_title(),
    'no_found_rows'  => false,
    'posts_per_page' => 6,
) );

$related_posts = array_merge( $cat_query->posts, $title_query->posts );

// Need to sort the posts so they're not grouped.
$dates = array_column( $related_posts, 'post_date' );
$related_posts = array_multisort( $related_posts, $dates, SORT_NATURAL );

// Limit to six posts.
$related_posts = array_slice( $related_posts, 0, 6 );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.