计算父类别中子类别的帖子

时间:2015-05-28 12:00:15

标签: php mysql wordpress categories hierarchy

Hallo Wordpress社区,

我需要你的帮助。

我有一个拥有多位作者的Woocommerce商店网站。在侧边栏中,我想按作者显示一个woocommerce产品类别列表(基于作者发布的帖子),并附有产品发布计数器。我使用2famousTV之后的代码,它可以通过作者和计数器获得类别。我修改了它,所以它只显示父类别。

<?php

global $post, $wpdb;

// This will get us a list of the categories that our Author has published in
$author = get_query_var('author');
$categories = $wpdb->get_results("

SELECT DISTINCT(terms.term_id) as ID, terms.name, terms.slug, tax.description
FROM $wpdb->posts as posts
LEFT JOIN $wpdb->term_relationships as relationships ON posts.ID = relationships.object_ID
LEFT JOIN $wpdb->term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id
LEFT JOIN $wpdb->terms as terms ON tax.term_id = terms.term_id
WHERE posts.post_status = 'publish' AND
posts.post_author = '$author' AND
tax.taxonomy = 'product_cat' 
ORDER BY terms.name ASC
");


// This loop picks up categories
foreach($categories as $category) : 

$catid = $category->ID;

// Now, inside the loop, we need to count how many posts that the Author has published.
$counter = "SELECT COUNT(*)
FROM $wpdb->posts
LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID =     $wpdb->term_relationships.object_id)
LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE $wpdb->term_taxonomy.term_id = $catid
AND $wpdb->term_taxonomy.taxonomy = 'product_cat'

// modification  

AND tax.parent = '0'

// modification end

AND $wpdb->posts.post_status = 'publish'
AND post_author = '$author'
";

$user_count = $wpdb->get_var($counter);

echo '<div class="archive_author">' . $category->name . '<br/><span    class="subcounter">' . $user_count . ' posts</span></div>';

endforeach; 

?>

来源:Link to original post by 2famous-tv

我的问题:

使用此代码,父类别计数器仅计算父类别中的项目,但不计算其子类别中的项目。如何使父类别计数器包含子类别的帖子而不实际将帖子分配到父类别?

Category_______________Counter_____________Posts

Parent-Category___________0__________________0

-Child-Category A_________2__________________2

-Child-Category B_________3__________________3

应该是:

Category________________Counter____________Posts

Parent-Category___________5__________________0

-Child-Category A_________2__________________2

-Child-Category B_________3__________________3

我尝试了几个Wordpress继承选项,例如&#34; wp_list_categories&#34;,&#34; get_terms&#34;和&#34; get_the_term&#34;但没有带来结果。这似乎是通过Mysql的唯一方法。我不够坚定,不能做到这一点。任何帮助都会受到欢迎!

0 个答案:

没有答案