Wordpress - 由自定义分类问题相关的帖子

时间:2010-06-08 01:10:58

标签: wordpress custom-taxonomy

我正在尝试根据custum分类法显示相关帖子。我在wordpress.org上发现了一个有问题的查询。但是,原始帖子在结果中多次重复。 (单词是我使用的自定义分类法的名称)似乎发生的是单个帖子根据showpost设置的数量而重复。任何想法都可能导致这种情况发生?

代码:

<?php
//for in the loop, display all "content", regardless of post_type,
//that have the same custom taxonomy (e.g. words) terms as the current post
$backup = $post;  // backup the current object
$found_none = '<h2>No related posts found!</h2>';
$taxonomy = 'words';//  e.g. post_tag, category, custom taxonomy
$param_type = 'words'; //  e.g. tag__in, category__in, but genre__in will NOT work
$post_types = get_post_types( array('public' => true), 'names' );
$tax_args=array('orderby' => 'none');
$tags = wp_get_post_terms( $post->ID , $taxonomy, $tax_args);
if ($tags) {
  foreach ($tags as $tag) {
    $args=array(
      "$param_type" => $tag->slug,
      'post__not_in' => array($post->ID),
      'post_type' => $post_types,
      'showposts'=>5,
      'caller_get_posts'=>1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <h3><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h3>
        <?php $found_none = '';
      endwhile;
    }
  }
}
if ($found_none) {
echo $found_none;
}
$post = $backup;  // copy it back
wp_reset_query(); // to use the original query again
?>

2 个答案:

答案 0 :(得分:0)

foreach循环中,您正在获得重复。该代码实际上是在说;

  1. 获取分类型$param_type
  2. 的所有条款
  3. 对于每个字词,请获取5个使用该字词标记的帖子
  4. 因此,如果您的帖子被标记为同一分类的多个术语,则可能会出现多次。

    您可以迭代地将查询的帖子添加到post__not_in数组中,以确保它们不会再次出现;

    1. $post_not_in = array($post->ID);

    2. 上方添加if ($tags) {
    3. 然后将post__not_in' => array($post->ID),行替换为post__not_in' => $post_not_in,

    4. 最后,在$post_not_in[] = get_the_ID();

    5. 之后,将while放入$found_none = '';循环中

答案 1 :(得分:0)

至于我,我使用this plugin进行自定义分类相关帖子。我希望插件可以帮助你解决问题。

相关问题