The code shown isn’t working as wished, what is wrong?
you’re using only the first tag : $first_tag = $tags[0]->term_id;
to grab posts from all tags you have to iterate the whole array until a max of 5. The code below ( untested) grabs a max of 25 posts theoretically using up to 5 tags..BUT if you have 25 posts belonging to the first tag you will have only posts related to the first tag anyway:
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$max=5;
$arrayTags=[];
for($k=0;$k<$max;$k++){
$arrayTags[]=$tags[0]->term_id;
}
$args=array(
'tag__in' => $arrayTags,
'post__not_in' => array($post->ID),
'posts_per_page'=>25,
'ignore_sticky_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="https://wordpress.stackexchange.com/questions/356552/<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php
endwhile;
}
wp_reset_query();
}
to be sure to grab 5 posts from 5 tags you should run 5 queries ( unless there’s a more efficient way to do that of which I’m not aware of )
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo 'Related Posts';
$max=count($tags) >5 ? 5 : count($tags) ;
$idsToExclude=[$post->ID];
//ob_start();
for($k=0;$k< $max ;$k++){
$args=array(
'tag__in' => $tags[$k]->term_id,
'post__not_in' => $idsToExclude,
'posts_per_page'=>5,
'ignore_sticky_posts'=>1 // caller_get_posts is deprecated
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
if(!in_array(get_the_id(),$idsToExclude)){
$idsToExclude[]=get_the_id(); // add this id to the exclusion for the next query
}
?>
<a href="https://wordpress.stackexchange.com/questions/356552/<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><br>
<?php
endwhile;
}
}
//echo ob_get_clean();
wp_reset_query();
}