我很好奇是否可以通过多个标签显示相关帖子。
我正在工作的网站每个帖子大约有5个标签。大多数帖子共有1个或2个标签。我想展示的相关帖子共有3-5个标签。
因此,我希望相关帖子能够通过查找具有最多共同标签的帖子并按降序显示来发挥作用。
假设我显示了3个相关帖子:relatedpost1有4个公共标记,relatedpost2有3个公共标记,relatedpost3有1个公共标记。
甚至有可能做到这一点吗?
目前,我正在尝试两种显示帖子的方式,但它们并没有发挥我所希望的作用:
第一种方法(code) 只显示带有共同标签的帖子。
<?php $orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
\'tag__in\' => $tag_ids,
\'post__not_in\' => array($post->ID),
\'posts_per_page\'=>3, // Number of related posts that will be shown.
\'caller_get_posts\'=>1
);
$my_query = new wp_query( $args );
if( $my_query->have_posts() ) {
echo \'<div id="relatedposts"><h3>Related Posts</h3><div class="relatedbreak"></div><ul id="relatedul">\';
while( $my_query->have_posts() ) {
$my_query->the_post(); ?>
<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(array(185, 185)); ?></a></div>
<div class="relatedcontent">
<center><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><div class="comments_text"><?php the_title(); ?></div></center></a>
</div>
</li>
<? }
echo \'</ul></div>\';
}
}
$post = $orig_post;
wp_reset_query(); ?>`
第二种方法(code) 只显示具有第一个公共标记的帖子。<?php
//for use in the loop, list 5 post titles related to first tag on current post
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo \'<div id="relatedposts"><h3>Related Posts</h3></div><div class="relatedbreak"></div>\';
$first_tag = $tags[0]->term_id;
$args=array(
\'tag__in\' => array($first_tag),
\'post__not_in\' => array($post->ID),
\'posts_per_page\'=>3,
\'caller_get_posts\'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<ul id="relatedul">
<li><div class="relatedthumb"><a href="<? the_permalink()?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_post_thumbnail(array(185, 185)); ?></a></div>
<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><div class="comments_text"><?php the_title(); ?></div></a></li>
</ul>
<?php
endwhile;
}
wp_reset_query();
}
?>
两种方式都很糟糕;我要么得到相当随机的帖子显示(因为我的大多数帖子至少有一个共同的标签),要么(对于一些帖子)没有得到相关的帖子(因为他们的共同标签是标签4或5)。任何帮助都将不胜感激。