首页 文章

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

提问于
浏览
1

我有一个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应该是第2162行/home/myuser/public_html/mysitedirectory/wp-includes/query.php中的数组警告:implode()[function.implode ]:第2162行/home/myuser/public_html/mysitedirectory/wp-includes/query.php中传递的参数无效

1 回答

  • 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 );
    

相关问题