简体   繁体   中英

Writing query using WP_Query

I have 2 categories cat-slug1 and cat-slug2. Where, cat-slug1 is a parent of cat-slug2. I want to write a query wherein I want those results that belong to cat-slug1 and cat-slug2.

If one post is marked for cat-slug2 but not marked for cat-slug1 then I do not want to pick up this record in the results.

How do I modify the code below so that it return me only those result which belong to cat-slug1 and cat-slug2

$paged2 = isset( $_GET['paged2'] ) ? (int) $_GET['paged2'] : 1;


$args2 = array('abc_category' => 'cat-slug1',   
               'abc_category' => 'cat-slug2',       
                      'post_type' => 'abc',
                'paged'     => $paged2,
                'posts_per_page' => 20,
                'orderby' => 'title',
                'order' => 'asc');  

            $query2 = new WP_Query( $args2 );

What about making two queries?

$posts_cat1 = array(...)
$posts_cat2 = array(...)

$posts_cat1_and_cat2 = [];
foreach($posts_cat1 as $post){
    if(in_array($post, $array_cat2)) array_push($posts_cat1_and_cat2, $post);
}

EDIT:

Note that if you expect only posts to be fetched by WP_Query you can replace it by get_posts . Here's a little update (untested):

function get_posts_by_cat($cat){
    $args = array('category'=>$cat);
    return get_posts($args);
}

$posts_cat1 = get_posts_by_cat('cat-slug1');
$posts_cat2 = get_posts_by_cat('cat-slug2');

$posts_cat1_and_cat2 = [];
foreach($posts_cat1 as $post){
    if(in_array($post, $array_cat2)) array_push($posts_cat1_and_cat2, $post);
}

More parameters: http://codex.wordpress.org/Template_Tags/get_posts

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