gpt4 book ai didi

php - 获取wordpress类别中的评论总数

转载 作者:行者123 更新时间:2023-11-29 02:31:40 24 4
gpt4 key购买 nike

我试图在 Wordpress 中找出一种方法来获取特定类别中的评论总数。我已经阅读了官方文档和函数引用,但没有成功。然而,我想出了下面的代码,但不幸的是,它只选择了一个 $termid(即它选择了第一个类别的第一个 termid)并在所有类别中显示结果。请帮忙。

<?php
$categories = get_categories( array(
'hide_empty' => 0,
'hierarchical' => 0,
'exclude' => '1' //exclude uncategorised
));
foreach($categories as $category): ?>
global $wpdb;

$catid = $category->cat_ID;
$catname = $category->name;

$count = "SELECT COUNT(*) FROM $wpdb->comments, $wpdb->terms WHERE term_id=$category->term_id";
$result = $wpdb->get_var($count);
?>

最佳答案

我修改了来自 WordPress forum 的查询得到你想要的。这种设置的“大”优势是它只会向数据库发出一个请求。但是,这确实意味着您需要修改脚本,但我认为这没什么大不了的。

这是查询

-- selects the comment count and term (category) name 
SELECT SUM(p.comment_count) AS count, t.name FROM wp_posts p
JOIN wp_term_relationships tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
JOIN wp_terms t ON t.term_id = tt.term_id
WHERE t.term_id in (1,2,3,4,5...)
AND p.post_status = 'publish'
GROUP BY t.term_id

下面是我将如何编写上面的代码。

<?php

global $wpdb;

$categories = get_categories(array(
'hide_empty' => 0,
'hierarchical' => 0,
'exclude' => '1' //exclude uncategorised
));

// create a comma separated string of category ids
// used for SQL `WHERE IN ()`
$category_ids = implode(',', array_map(function($cat) {
return $cat->term_id;
}, $categories));

$query = "SELECT SUM(p.comment_count) AS count, t.name FROM wp_posts p
JOIN wp_term_relationships tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy tt ON tt.term_taxonomy_id = tr.term_taxonomy_id
JOIN wp_terms t ON t.term_id = tt.term_id
WHERE t.term_id in ($category_ids)
AND p.post_status = 'publish'
GROUP BY t.term_id";

$categories = $wpdb->get_results($query);

echo '<ul>';
foreach( $categories as $category ) {
printf("<li>the %s category has %s comments</li>", $category->name, $category->count);
}
echo '</ul>';

关于php - 获取wordpress类别中的评论总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343559/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com