WP_Query to filter specific parent Custom Post Type?

时间:2016-04-07 10:51:44

标签: php wordpress custom-post-type

I have 2 custom post types created via theme, rt_book and rt_chapter. Each rt_book has several rt_chapter posts. When I use single-rt_book.php (which should show the contents of a specific rt_book post), how can I filter only the rt_chapter belongs to that specific rt_book being loaded?

My current WP_Query is as follow (which returns all 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;
    }
}

I relate these two custom post types by setting the Post Meta of rt_book with an array of rt_chapter post IDs, via function add_post_meta({post ID of rt_book}, 'chapter_orders', {post ID of rt_chapter}) and update_post_meta().

Tried child_of option of WP_Query, but does not affect the results.

2 个答案:

答案 0 :(得分:1)

尝试这样

$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;
 }
}

答案 1 :(得分:0)

试试这个。希望这应该有用。

$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
        ),
    )
);