I have a loop that in theory should display 4 related posts - by tag at first place AND when there are no enough tag related posts, it should take the remaining posts from the same category.
The code works fine when at least one tag is matching - the remaining 3 posts are taken from the same category. But if there are no tag related posts at all, the loop doesn't take all 4 posts from the same category. It just shows totally unrelated content from different category.
<?php
$max_articles = 4; // How many articles to display
echo ' <div id="carousel-related-posts" class="owl-carousel owl-theme relatedposts">';
$cnt = 0;
// Show articles based on the same tag
$article_tags = get_the_tags();
$tags_string = '';
if ($article_tags) {
foreach ($article_tags as $article_tag) {
$tags_string .= $article_tag->slug . ',';
}
}
$tag_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&tag=' . $tags_string);
if ($tag_related_posts) {
foreach ($tag_related_posts as $related_post) {
$cnt++;
$backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($related_post->ID), 'medium_large' );?>
<div class="header-wrap" style="background: url('<?php echo $backgroundImg[0]; ?>') no-repeat 50% 30%; background-size: cover;">
<header class="entry-header">
<div class="image-title">
<?php incomplete_cat_list($related_post->ID); ?>
<a class="post-title-link" href="<?php the_permalink($related_post->ID); ?>">
<?php print get_the_title($related_post->ID); ?>
</a>
</div>
</header>
</div>
<?php }
}
// Only if there's not enough tag related articles,
// add some from the same category
if ($cnt < $max_articles) {
$article_categories = get_the_category($post->ID);
$category_string = '';
foreach($article_categories as $category) {
$category_string .= $category->cat_ID . ',';
}
$cat_related_posts = get_posts('exclude=' . $post->ID . '&numberposts=' . $max_articles . '&category=' . $category_string);
if ($cat_related_posts) {
foreach ($cat_related_posts as $related_post) {
$cnt++;
if ($cnt > $max_articles) break;
$backgroundImg = wp_get_attachment_image_src( get_post_thumbnail_id($related_post->ID), 'medium_large' );?>
<div class="header-wrap" style="background: url('<?php echo $backgroundImg[0]; ?>') no-repeat 50% 30%; background-size: cover;">
<header class="entry-header">
<div class="image-title">
<?php incomplete_cat_list($related_post->ID); ?>
<a class="post-title-link" href="<?php the_permalink($related_post->ID); ?>">
<?php print get_the_title($related_post->ID); ?>
</a>
</div>
</header>
</div>
<?php }
}
}
echo '</div>';
?>
Any idea why this code doesn't take all related posts from the same category, when it doesn't find at least one tag related post?