Excluding posts not working

时间:2017-09-21 作者:Satrughna Sethy

我试了很多次,但没有得到正确的结果。有人请检查我的代码,我哪里做错了。

我想显示具有相同类别的其他帖子,但不是单个页面上显示的帖子,而是当前帖子的上一篇和下一篇帖子。有没有其他方式可以展示?

$thisid = get_the_ID();
$prevpost = get_previous_post();
$previd = $prevpost->ID;
$nextpost = get_next_post();
$nextid = $nextpost->ID;
$excludearray = array($previd, $thisid, $nextid);

$args = "posts_per_page=4&exclude=$thisid,$previd,$nextid&cat=";
$categories = get_the_category();
$i = 1;
foreach ($categories as $category) {
    if ($i == 1) {
        $args .= $category->term_id;
    } else {
        $args .= "," . $category->term_id;
    }
    $i++;
}
$query = new WP_Query($args);
if ($query->have_posts()):
    while ($query->have_posts()):
        $query->the_post();
    endwhile;
endif;
谢谢。

3 个回复
SO网友:Jan Boddez

看看https://codex.wordpress.org/Class_Reference/WP_Query, 也许可以尝试在数组中传递参数。上面的页面列出了这个确切的示例,应该可以:

// This WILL work
$exclude_ids = array( 1, 2, 3 );
$query = new WP_Query( array( \'post__not_in\' => $exclude_ids ) );

SO网友:Satrughna Sethy

谢谢大家的指导,我刚刚更改了代码。下面我正在写我的ans。

$thisid = get_the_ID();
$prevpost = get_previous_post();
$previd = $prevpost->ID;
$nextpost = get_next_post();
$nextid = $nextpost->ID;
$excludearray = array($previd, $thisid, $nextid);

$exclude_ids = array($previd, $thisid, $nextid);
$args = array(
    "posts_per_page" => 4,
    "post__not_in" => $exclude_ids
);
$categories = get_the_category();
$i = 0;
$cat = array();
foreach ($categories as $category) {
    $cat[$i] = $category->term_id;
    $i++;
}
$cats = array(
    "category" => $cat
);
$args = array_merge($args, $cats);
$query = new WP_Query($args);

if ($query->have_posts()):
    while ($query->have_posts()):
        $query->the_post();
            //Some design stuff.
    endwhile;
endif;
wp_reset_query();

SO网友:Z. Zlatev

你是get_posts() 中的参数WP_Query. 仅使用get_posts() 相反

结束