[英]Does get_query_var('cat') fetches child Category Posts as well?
在category.php中,我使用自定义查询来获取帖子:
<?php
$cat_id = get_query_var('cat');
$args = array(
'posts_per_page' => 2,
'orderby' => 'date',
'cat' => $cat_id
);
query_posts($args);
// the Loop
get_template_part('aa_HomeLoopMain');
?>
我正在使用get_query_var('cat')
来获取当前类别的类别帖子,我认为这只会给出带有$cat_id
的类别ID的类别帖子,而不是其子类别的帖子 ?
你做错了。 永远不要使用query_posts
,它会破坏主查询对象,重新运行查询,而且速度很慢,所有这些都会对性能和SEO以及依赖于主查询的其他功能产生负面影响。 另外,如果这是您的主要查询,则根本不应该使用自定义查询,而应使用pre_get_posts
在执行之前修改主要查询。
get_query_var(
cat )
仅返回查询的类别,而不返回其子类别。
您应该删除query_posts
部分并将以下内容添加到您的functions.php
add_action( 'pre_get_posts', function ( $q )
{
if ( !is_admin()
&& $q->is_main_query()
&& $q->is_category()
) {
$q->set( 'posts_per_page', 6 );
}
});
您应该总共查询6个帖子,我已经更新了。 您可以尝试以下循环
if ( have_posts() ) {
while( have_posts() ) {
the_post();
if ( 1 <= $wp_query->current_post ) {
// Add your markup for column one, this will display 2 posts
} else {
// Add your markup for column two, this will display 4 posts
}
}
}
由于某些原因,我无法从手机发布评论,但我认为您使用的代码有误。 我已经更新了代码以显示循环。 确实有效。 如果没有,则其他内容会破坏您的页面,例如query_posts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.