The question probably needs some clarification so here I go: I'm building a carousel displaying the titles of the 5 latest articles.
However, from a specific category (called schaft in my case) it should only display one post even though the 5 latest posts might have this category in there multiple times. If this is the case, it should display the latest one, but skip the following ones an jump to the next item in the query.
I've got this working by using two loop functions. The first one is checking if there are excess schaft categories in the query, skipping to the next one if necessary and repeating the whole function adding 1 to the number of posts the query has to display until it displays 5 posts even without the excess schaft categories. It will then run a function with the loop actually displaying the post titles The problem is that it has to repeat the query a lot of times and I'm pretty sure this is not efficient.
Maybe someone can tell me how to do this the right and efficient way? I've added my code for clarity.
function carouselimages( $postsinloop ) {
if ( !$postsinloop) { $postsinloop = 5; }
$i = 0;
$schaft = 0;
$schaft_duplicate_query = new WP_Query('posts_per_page='.$postsinloop);
while($schaft_duplicate_query->have_posts()) : $schaft_duplicate_query->the_post();
$category = get_the_category();
$category = $category[0]->slug;
if ( $category == 'schaft' ) {
$schaft++;
if ( $schaft >= 2 ) { continue; }
}
$i++;
endwhile;
wp_reset_postdata();
$postsinloop++;
if ( $i < 5 ) { carouselimages( $postsinloop ); }
if ( $i == 5 ) { carouselloop($postsinloop); }
}
