简体   繁体   English

使用WP_Query编写查询

[英]Writing query using WP_Query

I have 2 categories cat-slug1 and cat-slug2. 我有2类cat-slug1和cat-slug2。 Where, cat-slug1 is a parent of cat-slug2. 其中,cat-slug1是cat-slug2的父级。 I want to write a query wherein I want those results that belong to cat-slug1 and cat-slug2. 我想编写一个查询,其中我想要属于cat-slug1和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. 如果一个帖子被标记为cat-slug2但未标记为cat-slug1,那么我不想在结果中获得此记录。

How do I modify the code below so that it return me only those result which belong to cat-slug1 and cat-slug2 如何修改下面的代码,使其仅返回属于cat-slug1和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 . 请注意,如果您希望WP_Query仅获取帖子,则可以将其替换为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 更多参数: http : //codex.wordpress.org/Template_Tags/get_posts

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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