如何将自定义循环设置为仅显示顶级帖子?我有一个分层的自定义帖子类型,归档页面显示父帖子和子帖子。
如何通过WP_QUERY只显示循环中的顶级帖子?
3 个回复
最合适的回答,由SO网友:Manny Fleurmond 整理而成
此解决方案基于以下代码:Justin Tadlock. 在WordPress获取主循环的帖子之前调用pre\\u get\\u posts。基本上,您可以测试页面是否是post类型的存档,并确保未设置post\\u父级。然后将post\\u parent设置为0,这是顶级帖子的默认父级。非常简单。
<?php
//pre_get_posts filter is called before WordPress gets posts
add_filter( \'pre_get_posts\', \'my_get_posts\' );
function my_get_posts( $query ) {
//If the user is viewing the frontend, the page is an archive and post_parent is not set and post_type is the post type in question
if ( ! is_admin() && is_archive() && false == $query->query_vars[\'post_parent\'] && $query->query_vars[\'post_type\'] === \'my_post_type\')
//set post_parent to 0, which is the default post_parent for top level posts
$query->set( \'post_parent\', 0 );
return $query;
}
?>
SO网友:Ryan
您只需添加post_parent=0
到您的查询
SO网友:alds
从@Ryan的帖子中可以看出,关键是设置post_parent=0
和post_type=\'page\'
.
您始终可以查看WP\\U查询对象的SQL请求,以查看需要添加哪些参数才能获得所需的结果。
此代码适用于我:
<?php
$args=array(\'post_parent\' => 0, // required
\'post_type\' => \'page\', // required
\'orderby\' => \'menu_order\', // to display according to hierarchy
\'order\' => \'ASC\', // to display according to hierarchy
\'posts_per_page\' => -1, // to display all because default is 10
);
$query = new \\WP_Query( $args );
/* Uncomment to see the resulting SQL to debug
echo $query->request; die();
//*/
if ( $query->have_posts() ) {
while($query->have_posts()) {
$query->the_post();
$post_id=get_the_ID();
$post=get_post($post_id,\'ARRAY_A\');
echo $post[\'ID\'].\': \'.$post[\'post_title\'].\'<br>\';
}
}
结束