簡體   English   中英

與wordpress相關的帖子按類別重復

[英]wordpress related posts by category duplicating

我在使$ 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; ?>

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

在循環結束時,變量$ do_not_duplicate保存帖子的ID和所有相關帖子的ID。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM