0

我有一个奇怪的问题,一些帖子出现在它们不在的类别中。当我查看我的后台并按类别过滤时,一些帖子出现在那里,但它们没有被签入。

结果是他们也出现在前台。

这是我的 category.php (但我不认为这是问题)

<?php
get_header();
?>

<section id="wrapper" class="page <?php echo get_query_var('cat'); ?>">
    <div id="container">

        <?php 

            $category = get_category(get_query_var('cat'));
            $cat_id = $category->cat_ID;
            query_posts('showposts=1&cat='.$cat_id);

            if ( have_posts() ) : 

                while ( have_posts() ) : the_post();

                get_template_part( 'content', get_post_format() );

                endwhile;

            endif;
        ?>
    </div>
</section>
<?php
    get_footer();
?>

我查看了表格“_term_relationships”,一切都是正确的,它们没有属于错误的类别。

所以也许有人有线索找出答案?

PS:我正在使用 WPML,但如果我停用它,它就是同样的问题

4

2 回答 2

0

您不应该使用query_posts(),请参阅(https://wordpress.stackexchange.com/questions/1753/when-should-you-use-wp-query-vs-query-posts-vs-get-posts

尝试这个:

<?php 

            $category = get_category(get_query_var('cat'));
            $cat_id = $category->cat_ID;

            $args = array( 'category' => $cat_id );


             $query2 = new WP_Query($args);

            if ( $query2->have_posts() ) : 

                while ( $query2->have_posts() ) : 
                    $query2->the_post();

                    get_template_part( 'content', get_post_format() );

                endwhile;

            endif;
        ?>
于 2014-10-09T13:44:39.027 回答
0

首先,永远不要query_posts用来构造任何类型的查询

注意:此功能不适用于插件或主题。正如稍后解释的,有更好、性能更高的选项来更改主查询。query_posts() 是通过用新的查询实例替换页面的主查询来修改页面的主查询的过于简单和有问题的方法。它效率低下(重新运行 SQL 查询)并且在某些情况下会彻底失败(尤其是在处理帖子分页时)。

其次,永远不要在任何类型的存档页面或主页上更改自定义查询的主查询。正确的方法是pre_get_posts在主查询执行之前使用更改查询变量。看看我前段时间做的这个帖子

第三,Wordpress 中的类别页面确实以一种奇怪的方式工作。当访问类别页面时,它将显示来自所选类别的帖子和来自所选类别的子类别的帖子。我敢打赌这就是你所看到的。这是很正常的行为。如果您需要更改此设置,请查看@ialocin 在 WPSE 上的此答案。为了这个答案的利益,这里是解决方案

add_filter( 
    'parse_tax_query', 
    'wpse163572_do_not_include_children_in_category_archive_parse_tax_query' 
);
function wpse163572_do_not_include_children_in_category_archive_parse_tax_query( $query ) {
    if ( 
        ! is_admin() 
        && $query->is_main_query()
        && $query->is_category()
    ) {
        // as seen here: https://wordpress.stackexchange.com/a/140952/22534
        $query->tax_query->queries[0]['include_children'] = 0;
    }
}
于 2014-10-09T16:15:03.270 回答