自定义帖子类型和分类-显示相关帖子

时间:2012-10-01 作者:user643284

我有一个带有自定义服务分类的项目自定义帖子类型。每个项目都可以勾选多个服务。在项目页面上,我使用以下代码撤回相关项目

    <?php
//for in the loop, display all "content", regardless of post_type,
//that have the same custom taxonomy (e.g. genre) terms as the current post
$backup = $post;  // backup the current object
$found_none = \'\';
$taxonomy = \'services\';//  e.g. post_tag, category, custom taxonomy
$param_type = \'services\'; //  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) {
echo "<section class=\'divide\'>";
echo "<div class=\'container\'>";
echo "<h2 class=\'no-border\'>Related projects</h2>";
echo "<ul class=\'portfolio\'>";
  foreach ($tags as $tag) {
    $args=array(
      "$param_type" => $tag->slug,
      \'post__not_in\' => array($post->ID),
      \'post_type\' => $post_types,
      \'showposts\'=>3,
      \'caller_get_posts\'=>1
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      ?>
      <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <li>
          <a href="<?php the_permalink(); ?>">
            <img src="<?php $src = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), array( 315,225 ), true, \'\' ); echo $src[0]; ?>" />
            <h3><?php the_title(); ?></h3>
            <?php the_field(\'client\'); ?>
          </a>
        </li> 

        <?php $found_none = \'\';
      endwhile; ?>

      <?php
    }
  }
  echo \'</ul>\';
  echo "</div>";
  echo "</section>";
}
if ($found_none) {
echo $found_none;
}
$post = $backup;  // copy it back
wp_reset_query(); // to use the original query again
?>
起初,它看起来工作得很好,但仔细检查一下,如果一个项目有多个服务,那么它就是在复制被撤回的帖子。

有什么建议吗?有没有更好的方法(按分类法)收回相关帖子?如何阻止结果重复?

谢谢

1 个回复
SO网友:WhiskerSandwich

您正在为每个标记运行一个单独的查询,这除了浪费之外,还会导致重复发布。您应该重写代码,只进行一个查询来查找所有标记。尝试以下方法:

<?php

// Generate an array of taxonomy IDs
$tax_IDs = array();
foreach ($tags as $tag) {
    $tax_IDs[] = $tag->ID;
}

// Use your array of taxonomy IDs in the query args
$args = array(
  \'post_type\' => \'your_custom_post_type\',
  \'post__not_in\' => array($post->ID),
  \'showposts\'=> 3,
  \'tax_query\' => array(
        array(
            \'taxonomy\' => \'your_custom_taxonomy\',
            \'field\' => \'id\',
            \'terms\' => $tax_IDs
        )
    )
);

// Run your query
$my_query = new WP_Query($args);

?>

结束

相关推荐