从get_posts()中排除帖子

时间:2015-02-20 10:29:30

标签: php wordpress

早上好,我发现了很多类似的问题,但没有一个答案适合我的问题。重点非常简单:我有一个带get_posts()的自定义循环,我想排除显示的当前帖子。

代码是:

$args = array(
          'posts_per_page'    => 3,
          'orderby'           => 'meta_value',
          'order'             => 'ASC',
          'post_type'         => 'fasthomepress_pt',
          'post__not_in'      => array(get_the_id()),
          'meta_query'        => array(
                                    array(
                                        'key' => 'custom_richiesta',
                                        'value' => array($custom_boxes['custom_richiesta'][0] - 10000, $custom_boxes['custom_richiesta'][0] + 10000 ),
                                        'type' => 'numeric',
                                        'compare' => 'BETWEEN'
                                      )
                              )
      );

我尝试过:

'post__not_in' => array(get_the_ID),
'post__not_in' => array($post->ID),
'exclude'      => $post->ID,
'exclude'      => get_the_ID,

以及许多其他有或没有数组的组合。诅咒,当前post id在此循环之前正确回显,如果我尝试echo($ post-> ID)和echo(get_the_ID()),我会得到相同的,正确的结果。

我真的不知道发生了什么, 非常感谢你的帮助,

2 个答案:

答案 0 :(得分:15)

尝试exclude

$args = array(
      'posts_per_page'    => 3,
      'orderby'           => 'meta_value',
      'order'             => 'ASC',
      'post_type'         => 'fasthomepress_pt',
      'exclude'      => array(get_the_id()),
      'meta_query'        => array(
                                array(
                                    'key' => 'custom_richiesta',
                                    'value' => array($custom_boxes['custom_richiesta'][0] - 10000, $custom_boxes['custom_richiesta'][0] + 10000 ),
                                    'type' => 'numeric',
                                    'compare' => 'BETWEEN'
                                  )
                          )
  );

答案 1 :(得分:8)

这是一个能够做到这一点的函数:

    function get_lastest_post_of_category($cat){
    $args = array( 'posts_per_page' => 1, 'order'=> 'DESC', 'orderby' => 'date', 'category__in' => (array)$cat);
    $post_is = get_posts( $args );
    return $post_is[0]->ID;
}

用法:说我的类别ID是22,然后:

$last_post_ID = get_lastest_post_of_category(22);

你也可以将一系列类别传递给这个函数。

    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
    $args = array(
    'posts_per_page'   => 18,
     'paged'           => $paged,
    'offset'           => 0,
    'post__not_in'     => array($last_post_ID,),
    'category'         => '',
    'category_name'    => '',
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'include'          => '',
    'exclude'          => '',
    'meta_key'         => '',
    'meta_value'       => '',
    'post_type'        => 'post',
    'post_mime_type'   => '',
    'post_parent'      => '',
    'post_status'      => 'publish',
    'suppress_filters' => true
);
// The Query
$the_query = new WP_Query( $args );