如何在查询后按ID从结果中删除帖子?

时间:2019-02-28 作者:Robert Andrews

如果$posts 包含WP_Query 对于帖子,如何从对象中删除一个特定的按ID排序的帖子?

我不是说使用post__not_in 在查询之前。我说的是在结果出来后删除一个帖子。

1 个回复
最合适的回答,由SO网友:Antti Koskinen 整理而成

也许像这样的方法行得通?

// Assuming $posts = new WP_Query( $args );
$post_to_remove = 123;
// If using post objects
foreach ( $posts->posts as $i => $post ) {
  if ( $post_to_remove == $post->ID ) {
    unset( $posts->posts[$i] );
    break; // no need to continue the loop as the post has been found
  }
}
// If only IDs were queried
foreach ( $posts->posts as $i => $post_id ) {
  if ( $post_to_remove == $post_id ) {
    unset( $posts->posts[$i] );
    break; // no need to continue the loop as the post has been found
  }
}
// do your rendering while/for/foreach loop after sorting
EDIT 我想,你也可以跳过循环中的帖子。

<?php if (have_posts()) : ?>

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

        <?php if ( $post_to_remove == get_the_id() ) { continue; } ?>

    <?php endwhile; ?>

        <?php // Navigation ?>

    <?php else : ?>

        <?php // No Posts Found ?>

<?php endif; ?>

相关推荐

使用复杂的orderby过滤器对Query_Posts()进行排序

我正在尝试使用复杂的orderby场景来排序我的帖子,该场景使用CASE 和WHEN 语法。为此,我创建了一个过滤器:add_filter( \'posts_orderby\', \'order_properties_by_reference\', 10, 2 ); function order_properties_by_reference( $orderby, $wp_query ){ global $wpdb; $orderby = \"C