admin管理员组

文章数量:1410731

I want to display posts that are either

  • EITHER Post Type A
  • OR Post Type B but ONLY if they are also in CATEGORY 1

Is that at all posible? How do I built my custom query?

I want to display posts that are either

  • EITHER Post Type A
  • OR Post Type B but ONLY if they are also in CATEGORY 1

Is that at all posible? How do I built my custom query?

Share Improve this question asked Jan 6, 2020 at 15:26 Achim BaurAchim Baur 1
Add a comment  | 

1 Answer 1

Reset to default 0

First, take a look at this: https://developer.wordpress/reference/classes/wp_query/

You can filter by querying by post type, or in a single query (code between /* */).

<?php
//This is the first query
$query_A = array(
    'post_type' => 'post_type_A', 
    'post_status' => 'publish',
    //'cache_results' => true,
    'posts_per_page' => 10,
    'orderby' => 'date', 
    'order' => 'DESC',
    'fields' => 'ids'//add by Achim Baur
);
$query_A['tax_query'] = array(
    'relation' => 'OR',
    array(
        'taxonomy' => 'the_taxonomy_here',
        'terms' => $_REQUEST['term_here'],
    )
);
//End the first query

//This is the second query
$query_B = array(
    'post_type' => 'post_type_B', 
    'post_status' => 'publish',
    'cache_results' => true,
    'posts_per_page' => 10,
    'orderby' => 'date', 
    'order' => 'DESC',
    'fields' => 'ids'//add by Achim Baur
);
$query_B['tax_query'] = array(
    'relation' => 'OR',
    array(
        'taxonomy' => 'the_taxonomy_here',
        'terms' => $_REQUEST['term_here'],
    )
);
//End the second query

//merge IDs
$post_ids = array_merge($query_A,$query_B);


//This is the final query
$query = array(
    'post_type' => 'any', 
    'post_status' => 'publish',
    //'cache_results' => true,
    'posts_per_page' => 10,
    'orderby' => 'date', 
    'order' => 'DESC',
    'post__in' => $post_ids,
);

//or simply, any post type in one query
/*$query = array(
    'post_type' => 'any', 
    'post_status' => 'publish',
    'cache_results' => true,
    'posts_per_page' => 10,
    'orderby' => 'date', 
    'order' => 'DESC',
    'tax_query' => array(
        array(
            'taxonomy' => 'the_taxonomy_here',
            'terms' => $_REQUEST['term_here'],
        ),
    ),
);*/

$posts = new WP_Query($query);
while($posts->have_posts()){
    //Write something here
}
?>

本文标签: loopCustom query for certain post type OR another post type with a certain category