简体   繁体   中英

Query custom posts type by custom field on archive page

I'm using the following query in an archive-mypostype.php template to list custom posts with a specific custom field value.

$args = array(
   'numberposts'    => -1,
   'post_type'      => 'mypostype',
   'meta_key'       => 'custom_field_name',
   'meta_value'     => true,
   'paged'          => get_query_var( 'paged' ),
);

$wp_query = new WP_Query( $args );

if ( $wp_query->have_posts() ) : 
while ( $wp_query->have_posts() ) : $wp_query->the_post();

These posts are assigned to a custom taxonomy. The query works great on the root archive for the custom post type, but viewing each taxonomy archive page displays all posts and not just the posts for the current taxonomy. How do I amend the query so that its possible to only see the posts for the current taxonomy archive?

You can have a look to the WP_Query codex page and its taxonomy parameter, here

With this parameter, you will be able to retrieve posts in a certain taxonomy.

$args = array(
   'numberposts'    => -1,
      'post_type'      => 'mypostype',         
      'paged'          => get_query_var( 'paged' ),
      'meta_query'     => array(
           array(
               'key'=> 'custom_field_name',
               'value'=> 'true',
           )
      ),
      'tax_query' => array(
           array(
               'taxonomy' => 'your-taxonomy', // change this with the cpt taxonomy name
               'field'    => 'slug',
               'terms'    => get_query_var( 'category_name' ), // change it with the query var needed
           ),
       )
);

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM