【问题标题】:How to create related posts functionality for wordpress custom post type posts when one posts belongs to many categories当一篇帖子属于多个类别时,如何为wordpress自定义帖子类型帖子创建相关帖子功能
【发布时间】:2015-11-07 09:46:47
【问题描述】:

我需要在 wordpress 自定义帖子类型的单个页面中添加相关帖子功能。我有属于多个类别的帖子,并且帖子在显示其内容时在顶部显示两次,并且本身也显示在相关发布部分。我尝试使用此代码

<?php
        $backup = $post;  // backup the current object
        $found_none = '<h2>No related posts found!</h2>';
        $taxonomy = 'news-category';//  e.g. post_tag, category, custom taxonomy
        $param_type = 'news-category'; //  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'=>-1,
              '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(); ?>
                <div class="related_post_item">
                <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><?php the_title(); ?></a></h2>
                <div class="news_date"><?php echo get_the_date('F Y', $post->ID); ?></div>
                <?php $found_none = ''; ?>
                                </div>
            <?php  endwhile;
            }
          }
        }
        if ($found_none) {
        echo $found_none;
        }
        $post = $backup;  // copy it back
        wp_reset_query(); // to use the original query again
        ?>

每个帖子检查一个类别时效果很好,但是我有属于多个类别的帖子。在检查多个类别时如何正确检测相关帖子?

【问题讨论】:

    标签: wordpress related-posts


    【解决方案1】:

    嘿,我找到了一个简单的解决方案。跟踪当前帖子的 Id,并在显示我的循环时添加了以下代码

                $exclude = $GLOBALS['current_id'];
                $args=array(
                  "$param_type" => $tag->slug,
                   'post__not_in' => array($exclude),
                  'post_type' => $post_types,
                  'showposts'=>-1,
                  'caller_get_posts'=>1
                );
    

    就是这样!!

    【讨论】:

      猜你喜欢
      • 2016-05-13
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 2020-01-19
      • 2016-04-27
      • 1970-01-01
      • 2012-01-01
      相关资源
      最近更新 更多