如何在使用此特定格式时从类别中排除帖子

时间:2012-06-15 作者:Sledge81

我试图将某个类别的帖子排除在主页上。php。

我的主题中的代码如下:

query_posts(array(\'post__not_in\' => $featured_posts_array));
                if (have_posts()) :
                    while (have_posts()) : the_post(); ?>
                        <div <?php post_class() ?> id="post-<?php the_ID(); ?>">
                            <div class="categories">
                                <h3><?php the_categories_excerpt(); ?></h3>
我尝试在query\\u posts(函数)之前添加以下内容,但它没有任何作用。

function exclude_category( $query ) {
    if ( is_feed() ) {
        $query = set_query_var( \'cat\', \'-1\' );  
    }

    return $query;
}

add_filter( \'pre_get_posts\', \'exclude_category\' );
有什么格式我需要遵循吗?

1 个回复
最合适的回答,由SO网友:Chip Bennett 整理而成

第一don\'t use query_posts(). 把这个电话完全扔掉就行了。它会破坏一切。

第二个:

我尝试在query\\u posts(函数)之前添加以下内容,但它没有任何作用。

回调和add_action() 呼叫属于functions.php, 不在模板文件中。如果你直接把它放进去home.php, 把它从那里拿出来,放进去functions.php.

第三:

你的pre_get_posts() 过滤器使用if ( is_feed() ) 有条件的这个is_feed() 当输出RSS提要时,conditional返回true,而不是blog posts索引上的home.php). 尝试使用is_home() 相反

第四:

不要打电话set_query_var() 在您的回拨中。使用$query->set() 相反

将其放在一起functions.php

<?php
function wpse55358_filter_pre_get_posts( $query ) {
    // Let\'s only modify the main query
    if ( ! is_main_query() ) {
        return $query;
    }
    // Modify the blog posts index query
    if ( is_home() ) {
        // Exclude Category ID 1
        $query->set( \'cat\', \'-1\' );

        // Build featured posts array
        $featured_posts_array = featured_posts_slider();

        // Exclude featured posts
        $query->set( \'post__not_in\', $featured_posts_array );
    }
    // Return the query object
    return $query;
}
add_filter( \'pre_get_posts\', \'wpse55358_filter_pre_get_posts\' );
?>
问题你想排除哪些类别?你确定ID是1?

结束