WP_Query以筛选特定的父级自定义过帐类型


WP_Query to filter specific parent Custom Post Type?

我有两个通过主题创建的自定义帖子类型,rt_bookrt_chapter。每个rt_book都有几个rt_chapter帖子。当我使用single-rt_book.php(它应该显示特定rt_book帖子的内容)时,如何仅筛选属于正在加载的特定rt_bookrt_chapter

我当前的WP_Query如下(返回所有rt_chapter):

$args = array(
    'post_type'         => 'rt_chapter', // TODO: Filter specific book.
    'post_status'       => 'publish',
    'posts_per_page'    => -1,
    'caller_get_posts'  => 1,
    'orderby'           => 'date',
    'order'             => 'ASC'
);
$query = new WP_Query($args);
if($query->have_posts()) {
    while($query->have_posts()) {
        $query->the_post();
        $posts[] = $query->post;
    }
}

我通过函数add_post_meta({post ID of rt_book}, 'chapter_orders', {post ID of rt_chapter})update_post_meta()rt_book的post Meta设置为rt_chapter post ID的数组,从而将这两种自定义post类型关联起来。

尝试了WP_Querychild_of选项,但不影响结果。

像这样尝试

$args = array(
 'post_type'         => 'rt_chapter', 
 'post_status'       => 'publish',
 'posts_per_page'    => -1,
 'caller_get_posts'  => 1,
 'orderby'           => 'date',
 'order'             => 'ASC',
 'meta_query' => array(
     array(
         'key'    => 'rt_book',
         'value'  => get_post_meta(get_the_ID(), 'chapter_orders', true),
         'compare'=> 'IN'
     ),
  )
);
$query = new WP_Query($args);
if($query->have_posts()) {
 while($query->have_posts()) {
    $query->the_post();
    $posts[] = $query->post;
 }
}

试试这个。希望这能奏效。

$tax_slug = get_query_var('taxonomy');
$args = array(
    'post_type'         => 'rt_chapter', // TODO: Filter specific book.
    'post_status'       => 'publish',
    'posts_per_page'    => -1,
    'caller_get_posts'  => 1,
    'orderby'           => 'date',
    'order'             => 'ASC',
    'tax_query' => array(
        array(
            'taxonomy' => 'rt_book',
            'field'    => 'slug',
            'terms'    => $tax_slug
        ),
    )
);