简体   繁体   中英

wordpress related posts by category duplicating

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM