0

我在让 $do_not_duplicate 正常工作时遇到问题 我的博客上有几个标题重复,我需要它停止。这是我到目前为止所拥有的:

<?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; ?>
4

1 回答 1

0

您在 foreach 中有一段时间 (have_posts() ),这会产生重复。您可以将循环更改为以下内容:

<?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; ?>

在循环结束时,var $do_not_duplicate 保存帖子的 id 和相关帖子的所有 id。

于 2013-01-30T15:37:02.930 回答