<?php
$categories = get_the_category();
$child_cat = null;
foreach ($categories as $category) {
if ($category->parent != 0) {
$child_cat = $category;
break; // Stop after finding the first subcategory
}
}
if ($child_cat) {
$args = array(
'cat' => $child_cat->term_id,
'orderby' => 'rand',
'posts_per_page' => 7, // Correct parameter
'post__not_in' => array(get_the_ID())
);
$related = new WP_Query($args);
if ($related->have_posts()) {
echo '<div class="main_relp"><ul class="cur_rpost">';
while ($related->have_posts()) {
$related->the_post();
echo '<li><div class="relp">';
echo '<div class="img_relp">' . get_the_post_thumbnail() . '</div>';
echo '<div class="title_relp">' . get_the_title() . '</div>';
echo '</div></li>';
}
echo '</ul></div>';
wp_reset_postdata();
}
}
?>
Explanation
Removed if( 0 != $related->current_post )
to ensure all posts are displayed.
Changed showposts
to posts_per_page
for correct parameter usage.
This will now display the correct number of related posts based on the subcategory.
I’d love to hear your feedback on this solution!
Did it solve your issue?