WordPress WP_Query - 仅查询父页面
问题描述:
我正在使用WP_Query来查询我的自定义帖子类型帖子。此自定义帖子类型具有父页面和子页面。我试图拉第一个父页面。我将如何做到这一点?WordPress WP_Query - 仅查询父页面
答
$parent_only_query = new WP_Query(array(
'post_type' => 'my-custom-post-type',
'post_parent' => 0
));
while ($parent_only_query->have_posts()){
$parent_only_query->the_post();
// etc...
}
wp_reset_query(); // if you're not in your main loop! otherwise you can skip this
答
一旦你已经运行查询,你通过它循环,你可以用$post->post_parent
访问每个岗位的父的ID,并且如果不为空,你可以得到这个职位的内容与get_post()
:
答
您可以通过查询数据库来实现此功能;
<?php
$parent_posts= $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_parent=0 AND post_type='page' AND post_status='publish' ORDER BY menu_order ASC");
foreach($parent_posts as $record){ ?>
<a href="<?php echo get_permalink($record->ID) ?>" >
<h1><?php echo $record->post_title; ?></h1>
</a>
<p><?php echo $record->post_title;?></p>
<?php } ?>
注: - $wpdb
是全局变量。