Leo
Leo

Reputation: 580

Wordpress counting posts wrong

What I'm trying to do: The posts can be categorized as A or B types. And I want to do an Archive that counts how many posts are categorized as A, how many are in B, and the total.

The problem: My code counts like 12 posts for category A. It counts 5 for category B. But it counts 12 for both category.

Why?

My code:

$posts_a = new WP_Query('cat=5&category__and=30');
$count_a = $posts_a->post_count;
//gives 12

$posts_b = new WP_Query('cat=5&category__and=29');
$count_b = $posts_b->post_count;
//gives 5

$posts_all = new WP_Query('cat=5');
$count_all = $posts_all->post_count;
//gives 12. It should be at least 12+5.

I don't want just to sum A+B. I want to know what is wrong.

Thanks

Upvotes: 1

Views: 2247

Answers (1)

Munim
Munim

Reputation: 6510

It doesn't look like you have just two categories, looking at your queries. From what I can, there are three categories, A, B and C.

There are 12 posts in categories A and B, and 5 in categories A and C, from what I can see from your queries and results.

You are also using category__and incorrectly, which may be the cause of the confusion.

Can you tell me what are the two category IDs you are searching for? I will post the queries after you mention them.

Edit: You probably need this:

$posts_a = new WP_Query(array('category__and'=>array(5,30),'posts_per_page'=>-1));
$count_a = $posts_a->post_count;

$posts_b = new WP_Query(array('category__and'=>array(5,29),'posts_per_page'=>-1));
$count_b = $posts_b->post_count;

$posts_all = new WP_Query('cat=5&posts_per_page=-1');
$count_all = $posts_all->post_count;

Also, this is probably an obvious answer and I don't know your category structure, but is 29 a child category of 30?

Upvotes: 3

Related Questions