I've written a small script to retrieve and display 4 random posts from the same category as the main post. The problem is 6 posts in this category (tagged Q&A) have the same image. So if the script displays two or three Q&A posts, it displays the same image 2-3 times.
Is it possible to limit the query to retrieve 4 posts from a category, but only include 1 of the posts that share the Q&A tag and image?
This is the function I'm currently using:
function wcr_related_posts($args) {
global $post;
$category = get_the_category();
// default args
$common_args = array(
'numberposts' => 4,
'orderby' => 'rand',
'order' => 'DESC',
'meta_query' => array(
'key' => '_thumbnail_id',
'compare' => 'EXISTS'),
'post_type' => "post",
'post_status' => "publish",
'post__not_in' => array($post->ID)
);
$cat_search_args = array(
'tax_query' => array(
array(
'taxonomy' => 'category',
'field' => 'name',
'terms' => $category[0]->name
)
));
$feature_posts_args = array(
'post__in' => array( 705, 1883, 4897, 3967, 3766, 3585, 2698, 2412, 2203, 2575, 282, 4040)
);
if ( in_array($category[0]->name, array('Erotic Hypnosis', 'Dominance and Submission', 'Sexual Health'))&& is_page()!== true){
$args = wp_parse_args($cat_search_args, $common_args);
}else {
$args = wp_parse_args($feature_posts_args, $common_args);
}
// use for diagnostics only
// print_r($args);
// query
$related_posts = get_posts($args);
// get template
include_once( __DIR__ . '/relatedposts-template.php');
wp_reset_postdata();
}