频率表-自定义SQL查询:
您可以尝试以下自定义查询,以获取给定分类法、帖子状态和类型的帖子/术语统计信息:
/**
* Frequency data: Count how many posts have a given number of terms,
* for a given post type, post status and taxonomy.
*
* @param string $taxonomy Taxonomy slug
* @param string $post_status Post status (draft, publish, ...)
* @param string $post_type Post type (post, page, ...)
* @return array Array containing freq. data with \'total\' (posts) and \'term\' counts
*/
function get_post_terms_stats_wpse_184993(
$taxonomy = \'post_tag\',
$post_status = \'publish\',
$post_type = \'post\'
){
global $wpdb;
$sql = "
SELECT COUNT( s.terms_per_post ) as total, s.terms_per_post
FROM (
SELECT COUNT( tr.object_id ) terms_per_post, tr.object_id
FROM {$wpdb->term_relationships} tr
LEFT JOIN {$wpdb->term_taxonomy} tt USING( term_taxonomy_id )
LEFT JOIN {$wpdb->posts} p ON p.ID = tr.object_id
WHERE tt.taxonomy = \'%s\'
AND p.post_status = \'%s\'
AND p.post_type = \'%s\'
GROUP BY tr.object_id
) as s
GROUP by s.terms_per_post
ORDER BY total DESC";
return $wpdb->get_results(
$wpdb->prepare( $sql, $taxonomy, $post_status, $post_type ),
ARRAY_A
);
}
安装约10k个帖子的示例:以下是已发布帖子中类别的示例:
$stats = get_post_terms_stats_wpse_184993(
$taxonomy = \'category\',
$post_status = \'publish\',
$post_type = \'post\'
);
print_r( $stats );
具有以下输出:
Array
(
[0] => Array
(
[total] => 8173
[terms_per_post] => 1
)
[1] => Array
(
[total] => 948
[terms_per_post] => 2
)
[2] => Array
(
[total] => 94
[terms_per_post] => 3
)
[3] => Array
(
[total] => 2
[terms_per_post] => 4
)
[4] => Array
(
[total] => 1
[terms_per_post] => 6
)
[5] => Array
(
[total] => 1
[terms_per_post] => 8
)
)
我们可以将其输出到HTML表中:
foreach( $stats as $row )
{
$rows .= sprintf(
"<tr><td>%d</td><td>%d</td></tr>",
$row[\'total\'],
$row[\'terms_per_post\']
);
}
printf( "<table><tr><th>#Posts</th><th>#Terms</th></tr>%s</table>", $rows );
具有以下输出:
所以在这里,我们可以看到有多少帖子有一定数量的术语,按顺序排列。
目前,SQL查询使用临时和文件排序,因此肯定有机会对其进行调整。在10k POST安装上,这在我的小型VPS上运行不到0.2秒。例如,我们可以删除post表连接以使其更快,但这样会变得不太灵活。
我们还可以缓存输出,例如使用@Pieter Goosen在回答中提到的瞬态API。