2

我正在尝试从显示最新帖子的简码中排除一个类别。我已经寻找了一段时间的解决方案,但似乎无法让不同的选项起作用。

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

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

猫 id 是 23。我尝试将 'exclude'=> '23', 添加到数组中,但这不起作用。任何建议或任何能够指出我正确方向的人将不胜感激!

4

1 回答 1

2

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

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

话虽如此,此代码将使用 query_posts 排除类别 1、2 和 3:

编辑:删除“array_merge”和不必要的措辞 'post', 'order' => 'DESC', 'cat' => '-1,-2,-3', 'posts_per_page' => 4 ); 查询帖子($args);?>

如果您选择使用 get_posts,它可能看起来像这样:'post', 'order' => 'DESC', 'cat' => '-1,-2,-3', 'posts_per_page' => 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' );
于 2013-08-15T16:29:46.043 回答