从循环中排除带有META_KEY的前2个帖子

时间:2016-09-07 作者:Phil

我在一页上有两个循环。第一个显示2个特色帖子:

<?php
$args = array(
    \'posts_per_page\' => \'2\',
    \'meta_query\' => array(
        array(
            \'key\' => \'featured_post\',
            \'value\' => \'1\',
            \'compare\' => \'LIKE\'
        )
    )
);
query_posts($args);
?>
第二个显示所有帖子:

<?php wp_reset_query(); ?>
                <?php if (have_posts()) : ?>
                    <?php while (have_posts()) : the_post(); ?>

                <div class="meta">DO STUFF</div>

                    <?php endwhile; ?>
                <?php endif; ?>
如何从第二个循环中排除前2个“featured\\u post”项目?

1 个回复
SO网友:jdm2112

第一点是,您不应该使用query_posts() 用于自定义查询。更好的方法是使用WP_Query 班更多信息请访问WP docshere.

此示例将显示您的2篇特色文章,然后在第二次查询中排除它们。

// We will push the ID of your featured posts to this array
$excl_posts[] = \'\';

// Query arguments from your featured posts query
$feat_args = array(
    \'posts_per_page\' => \'2\',
    \'meta_query\' => array(
        array(
            \'key\' => \'featured_post\',
            \'value\' => \'1\',
            \'compare\' => \'LIKE\'
        )
    )
);

// Instantiate new WP_Query instead of using query_posts()
$featured = new WP_Query( $feat_args );

if ( $featured->have_posts() ):
  while ( $featured->have_posts() ):
    $featured->the_post();

    // Do stuff with each posts
    echo get_the_title() . "<br>";

    // Push current postID onto the exclude array
    $excl_posts[] = get_the_ID();
  endwhile;
endif;

wp_reset_postdata();

$excl_feat_args = array(
    \'posts_per_page\' => \'10\',
    \'post__not_in\' => $excl_posts,
    \'meta_query\' => array(
        array(
            \'key\' => \'featured_post\',
            \'value\' => \'1\',
            \'compare\' => \'LIKE\'
        )
    )
);
$excl_featured = new WP_Query( $excl_feat_args );

if ( $excl_featured->have_posts() ):
  while ( $excl_featured->have_posts() ):
    $excl_featured->the_post();
    echo get_the_title() . "<br>";
  endwhile;
endif;

wp_reset_postdata();

相关推荐

当in_the_loop()为假时,何时以及为什么is_Single(‘my_cpt’)为真?

我正在使用模板系统的示例代码。此地址的页码:http://project.test/my_cpt/hello-post/.无法理解原因is_singular( \'my_cpt\' ) 是true 虽然in_the_loop() 是false.在页面模板中The Loop "E;“工程”:if ( have_posts() ) { while ( have_posts() ) { the_post(); ?>