query_posts($ args)排除一个类别

时间:2013-08-15 16:08:30

标签: php arrays wordpress categories args

我正在尝试从显示最新帖子的短代码中排除某个类别。我已经搜索了一段时间来解决这个问题,但似乎无法获得不同的选择。

这是我的代码,(不幸的是我没有写它但需要编辑它):

function blogcuts_homepage_sc($atts, $content = null) {
    $blogH = '';
    $last = '';
    $counter = 1;
    $args = array(
        'post_type' => 'post',
        'order' => 'DESC',
        'posts_per_page' => 4
    );
    query_posts( $args );
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    if ($counter == $args['posts_per_page']) { $last = ' last-column'; }
        $img_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'small');
        $comments = get_comments_number();
        $custom = get_post_custom();

        $blogH.= '<article class="blog-excerpt'.$last.'">';
        $blogH.= '<h3><a class="bg-transition" href="'.get_permalink(get_the_ID()).'">'.get_the_title().'</a></h3>';
        $blogH.= '<a href="'.$img_array[0].'" rel="prettyPhoto" title="'.get_the_title().'">';
        $blogH.= get_the_post_thumbnail($post->ID, 'item', array('title'    => get_the_title()));
        $blogH.= '<div class="meta"><span class="date">'.get_the_date().'</span><div class="alignright"><span class="number-of-comments">'.$comments.'</span><a class="comments" href="'.get_permalink(get_the_ID()).'#comments"></a>';

        if (get_option('op_likeit') == 'Enabled') {
            $blogH.= '<span class="number-of-likes likes-'.get_the_ID().'">'.likes(get_the_ID()).'</span><a id="likeit-'.get_the_ID().'" class="liked-after-'.get_the_ID().' likes likeit'.liked(get_the_ID()).'" href="#"></a>';
        }
        $blogH.= '</div></div><p class="excerpt">'.$custom['desc'][0].'</p></article>';
        $counter++;
        endwhile; endif;
        wp_reset_query();
        return $blogH;
    }
}
add_shortcode("blogcuts_homepage", "blogcuts_homepage_sc");

cat id为23.我尝试添加'exclude'=&gt; '23',到阵列,但这不起作用。任何建议或任何能够指出我正确方向的人都将不胜感激!

1 个答案:

答案 0 :(得分:2)

编辑:get_posts()是执行此操作的首选方法,我认为,因为它不会干扰the_loop()(见下文)你确定要使用query_posts()而不是get_posts()?

Query_posts改变主循环,当用户将短代码添加到页面然后他们的页面“中断”时,这可能会导致意外行为。

话虽这么说,此代码将使用query_posts排除类别1,2和3:

编辑:删除“array_merge”和不必要的verbage      “后”,             'order'=&gt; 'DESC',             'cat'=&gt; '-1,-2,-3',             'posts_per_page'=&gt; 4     );     query_posts($ args);     ?&GT;

如果您选择使用get_posts,它可能看起来像这样:      “后”,         'order'=&gt; 'DESC',         'cat'=&gt; '-1,-2,-3',         'posts_per_page'=&gt; 4     );

$myposts = get_posts( $args );
foreach ( $myposts as $post ) : setup_postdata( $post ); ?>
    ....  now you can operate just like in the_loop()
endforeach; 
wp_reset_postdata();
?>

http://codex.wordpress.org/Class_Reference/WP_Query

Exclude Posts Belonging to Category

Display all posts except those from a category by prefixing its id with a '-' (minus) sign.

$query = new WP_Query( 'cat=-12,-34,-56' );