两个循环,从第二个循环中的第一个循环中排除post

时间:2012-09-22 01:27:48

标签: wordpress

我有一个wordpress页面,它有两个循环,如此......

<?php 
global $post;
$args = array(
    'showposts'        => 1,
    'category_name'    => 'videos',
    'meta_key'         => 'feature-image',
);

$myposts = get_posts($args);  
foreach( $myposts as $post ) :  setup_postdata($post);
$exclude_featured = $post->ID;
?>
<span class="featured">
<?php the_title(); ?>
</span>
<?php endforeach; ?>

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

现在我需要在我的第二个循环中使用$ exclude_featured一些如何从该循环中排除该帖子。我尝试了一些实现,但没有一个有效。我尝试在第二个循环的while语句上面添加以下内容......

global $query_string;
query_posts( $query_string . '&exclude='.$exclude_featured );

这......

global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'exclude' => $exclude_featured ) );
query_posts( $args );

..并且没有运气。我注意到,通过使用这两个片段中的任何一个,它们还会渲染我的pre_get_posts函数,该函数设置显示无用的帖子数。

任何帮助将不胜感激

编辑:

我尝试在第二个循环的while语句之前添加以下行。

global $wp_query;
$args = array_merge( $wp_query->query_vars, array( 'post__not_in' => $exclude_featured ) );
query_posts( $args );

但是我仍然没有取得任何成功,它会出现以下错误:

  

警告:array_map()[function.array-map]:参数#2应为a   数组   /home/myuser/public_html/mysitedirectory/wp-includes/query.php在线   2162

     

警告:implode()[function.implode]:传入的参数无效   /home/myuser/public_html/mysitedirectory/wp-includes/query.php在线   2162

1 个答案:

答案 0 :(得分:1)

您可以用以下代码替换最后三行:

<?php
while ( have_posts() ) : the_post();
if ( $exclude_featured == get_the_ID() )
    continue;

the_title();
endwhile;
?>
循环结构中使用

continue来跳过当前循环迭代的其余部分,并在条件评估和下一次迭代开始时继续执行。

但是,这会导致您显示的帖子少一个。如果您希望保持帖子计数完全相同,则需要在查询中排除帖子。问题中的查询非常接近正确,但post__not_in必须是一个数组,而不是整数。您需要做的就是将$exclude_featured包装在一个数组中,您的查询应该可以正常工作。

您的查询应如下所示:

global $wp_query;
$args = array_merge(
    $wp_query->query_vars,
    array(
        'post__not_in' => array(
            $exclude_featured
        )
    )
);
query_posts( $args );