【问题标题】:Querying Different Categories in Different Loop With Different Offsets用不同的偏移量在不同的循环中查询不同的类别
【发布时间】:2021-01-19 17:13:05
【问题描述】:

我有四个循环。在第一个循环中,我想显示所有类别的所有当前文章(突发新闻)。在第二个循环中,仅应显示类别为 4、5、6、7 的文章。但是,如果在第 1 个循环中发布了来自这些类别的文章,则该最新文章不应出现在第 2 个循环中。到目前为止,我只阅读了有关文章的一般排除,但没有阅读有关条件的内容。

【问题讨论】:

    标签: wordpress loops foreach offset


    【解决方案1】:

    你必须使用category__not_in:

    $include_cats = array( 4, 5, 6, 7 );
    $exclude_cats = array( 3 ); // 'breaking news' TERM ID
    
    $posts_args = array(
        'post_type'             => 'post',
        'post_status'           => 'publish',
        'posts_per_page'        => 4 ,
        'ignore_sticky_posts'   => true,
        'category__in'          => $include_cats,
        'category__not_in'      => $exclude_cats,
        'orderby'               => 'date',
    
    );
    
    $posts = new WP_Query( $posts_args );
    
    if ( $posts->have_posts() ) {
        while ( $posts->have_posts() ) {
            $posts->the_post();
            ?>
            <a href="<?php echo get_the_permalink( $posts->post->ID ); ?>" title="<?php echo get_the_title( $posts->post->ID ); ?>">
                <?php
                if ( has_post_thumbnail( $posts->post->ID ) ) {
                    echo get_the_post_thumbnail( $posts->post->ID, $img, array( 'class' => 'post-thumb' ) ); // YOUR IMAGE SIZE
                } else {
                    echo '<img class="' . $img . '" src="placeholder.png" width="150" height="150" alt="' . get_the_title( $posts->post->ID ) . '">'; //ADD PLACEHOLDER IMAGE HERE
                }
                ?>
                <h3 class="post-title"><?php echo get_the_title( $posts->post->ID ); ?></h3>
                <span class="author"><?php echo get_the_author( $posts->post->ID ); ?></span>
            </a>
            <?php
        }
    }
    
    wp_reset_postdata();
    

    【讨论】:

    • 感谢您的回复。一开始我也想到了你的方法。唯一的问题是,如果我在第一个循环(例如 24)中发布具有不同类别 ID 的文章,那么帖子不会滑入第二个循环。他们仍然被排除在外。你懂我的意思吗。我想我需要以某种方式比较帖子 ID。我需要确定第一个循环中的帖子 ID 并使用第二个循环运行查询。如果post ID相等,则该item可能不会出现在第二个循环中,如果不相等,它可能会出现在第二个循环中,只要允许它出现在类别ID之后即可。
    • 我有解决方案:&lt;h2&gt;Loop n°1&lt;/h2&gt; &lt;?php $ids = array(); while (have_posts()) : the_post(); the_title(); ?&gt; &lt;?php $ids[]= $post-&gt;ID; endwhile; ?&gt; &lt;h2&gt;Loop n°2&lt;/h2&gt; &lt;?php query_posts("showposts=50"); while (have_posts()) : the_post(); if (!in_array($post-&gt;ID, $ids)) { the_title();?&gt; &lt;?php } endwhile; ?&gt; 从这里:[链接] (isitwp.com/avoid-duplicate-posts-in-multiple-loops)
    猜你喜欢
    • 2020-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多