显示的代码没有按预期工作,怎么了?
您只使用了第一个标记:$first_tag = $tags[0]->term_id;
要从所有标签中获取帖子,您必须迭代整个数组,直到最大值为5。下面的代码(未测试)理论上最多可以使用5个标签获取25篇文章。。但是,如果您有25篇属于第一个标记的帖子,那么无论如何,您只会有与第一个标记相关的帖子:
$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="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a>
<?php
endwhile;
}
wp_reset_query();
}
为了确保从5个标签中抓取5篇文章,您应该运行5个查询(除非有更有效的方法,我不知道)
$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="<?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();
}