【问题标题】:Wordpress - Don't display posts which were already displayed in another loopWordpress - 不要显示已经在另一个循环中显示的帖子
【发布时间】:2017-04-16 03:29:27
【问题描述】:

我的网站上有 2 个部分:第一个是热门帖子(基于视图),第二个是最近的帖子。 如果帖子已经在热门帖子部分,我不希望它显示在“最近的帖子”部分。下面是我的代码。在第一个循环中,我创建了一个数组来存储该部分中的所有帖子 ID。在第二个循环中,我检查 id 是否在该数组中(可能不是最佳解决方案)。 由于某种原因,它只适用于第一个副本,即使$cont 变为true 所需的次数(我检查了echo)。那么是什么给了?

 <?php
    $popularpost = new WP_Query( array( 'posts_per_page' => 4, 'meta_key' => 'wpb_post_views_count', 'orderby' => 'meta_value_num', 'order' => 'DESC'  ) );
    $counter=0;
    $post_ids = array();
    while ( $popularpost->have_posts() ) : $popularpost->the_post(); 
        $postID = get_the_ID();
        $post_ids[$counter] = $postID;
     ?>
    <a href="<?php the_permalink(); ?>" class="" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>

    <?php $counter++; ?>
    <?php   endwhile; ?>

    <?php $myquery = new WP_Query('posts_per_page=6');
    while ( $myquery->have_posts() ) : $myquery->the_post(); ?>
    <?php $post_id = get_the_ID(); ?>
    <?php $post_ids_length = count($post_ids); ?>
    <?php for ($i=0; $i < $post_ids_length; $i++) {
            if ($post_id == $post_ids[$i]) {
                $cont = "true";
            } else {
                $cont = "false";
            }
    } ?>
    <?php if ($cont == "true") {
        continue;
    } ?>

    <a href="<?php the_permalink(); ?>" class=""><?php the_title(); ?></a>
    <?php endwhile; ?>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    如下更新您的第二个查询:

    $args2 = array('post__not_in' => $post_ids,'posts_per_page' => 6 );
    $myquery = new WP_query($args2);
    

    然后使用 While 循环遍历结果。

    【讨论】:

    • 谢谢,它成功了。但我很好奇为什么我的代码不起作用,你知道为什么吗?
    • 您的代码是错误的,因为当您找到一个等于流行 id 的 id 时,您不会退出 for 循环,所以您继续,如果它不是数组中的最后一个 $cont 变量将是在下一个循环中设置为 false。所以你的代码只适用于一个帖子,它是数组中的最后一个 id。如果您添加'break;',您的代码将有效在'$cont = "true";'之后
    • @kulan 我建议编写优化代码,如果有选项可以传入查询本身,那么我们不应该去自定义实现。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    相关资源
    最近更新 更多