简体   繁体   中英

Wordpress Query - Get Posts In BOTH (2) Categories

Actually, what I have is this:

CATEGORY1
-Subcat1
-Subcat2

CATEGORY2
-Subcat3
-Subcat4

Subcats of course being the child categories of their parent categories.

What I need is to get the posts that belong to Subcat1 of CATEGORY1 'AND' (means that I need both conditions to be true) posts that belong to ANY of the Subcats of CATEGORY2.

I tried this, but it doesn't work unless the user ticks both the parent category and the subcategory when assigning a post:

$query = new WP_Query(array("post_type" => "XYZ", "category__and" => array(CATEGORY1->Subcat1,CATEGORY2), "posts_per_page"=>-1));

Sidenote: CATEGORY1->Subcat1 is a variable that was previously defined in the code, but I just wrote it this way for the sake of demonstrating the query. All the arguments of the array are corresponding IDs.

WP_query treats subcategories as categories of their own. So, you could easily use $query = new WP_Query( 'category_name=Subcat1,Subcat3,Subcat4' );

Check WP_query Categories parameters

If the condition is a post to be tagged by both categories, you can concatenate categories rather than list them in the argument var.

'category_name' => 'News+Featured'

instead of

'category_name' => 'News,Featured'

That way the result will return posts only when both categories are checked for a post.

您可以在 WP_Query 中使用+代替,

WP_Query(array("category_name" => " Subcat1+CATEGORY2 "));

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