dte66654 2013-01-30 14:40
浏览 20
已采纳

wordpress相关帖子按类别重复

I am having an issue getting the $do_not_duplicate working properly I have several title duplicating on my blog and i need it to stop. Here is what i have so far:

<?php if (is_single()): ?>
<section>
<h3>Related Posts</h3>
<?php 
            global $post;
            $cats = wp_get_post_categories($post->ID);
            $do_not_duplicate[] = $post->ID; 
            if ( count ( $cats ) > 0):
            $args = array( 'numberposts' => 3, 'category' => implode($cats, ","), 'exclude' => $post->ID, 'post__not_in' => $do_not_duplicate );
            $related_posts = get_posts( $args );
            if (count($related_posts)): ?>

            <ul>
                <?php foreach ($related_posts as $post) :  setup_postdata($post); ?>
                <li><a href="<?php the_permalink() ?>"><?php while ( have_posts() ) : the_post(); $do_not_duplicate[] = $post->ID; if ( get_the_title() ) the_title(); else the_ID(); ?><?php 
endwhile; 
wp_reset_query(); ?>
                </a></li>

                <?php endforeach; ?>
            </ul>




            <?php else: ?>
            <p>No related posts found.</p>
            <?php endif; ?>
            <?php else: ?>
            <p>No related posts found.</p>
            <?php endif; ?>

        </section>
        <?php endif; ?>
  • 写回答

1条回答 默认 最新

  • doufubu2518 2013-01-30 15:37
    关注

    you have a while (have_posts() ) within a foreach and this produces the duplication. You may change your loop to something like this:

    <?php 
            global $post;
            $cats = wp_get_post_categories($post->ID);
            $do_not_duplicate[] = $post->ID; 
            if ( count ( $cats ) > 0):
            $args2 = array( 'numberposts' => 3, 'category' => implode($cats, ","), 'exclude' => $post->ID, 'post__not_in' => $do_not_duplicate );
            $related_posts = get_posts( $args2 );
            if (count($related_posts)): 
      ?>
    
      <ul>
        <?php foreach ($related_posts as $post) :  setup_postdata($post); ?>
                <li><a href="<?php the_permalink() ?>" ><?php $do_not_duplicate[] = $post->ID; if ( get_the_title() ) the_title(); else the_ID(); ?></a></li>
        <?php endforeach; ?>
            </ul>
            <?php wp_reset_query(); ?>
      <?php endif;endif; ?>
    

    At the end of the loop, the var $do_not_duplicate save the id of the post and all the id of the relative posts.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机数字电压表电路组成及框图
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line