列出每个自定义分类的帖子数和特定的自定义字段值

时间:2012-11-17 作者:gipson

我想按特定的分类法列出我的帖子。同时,对于每个分类法,我想计算具有特定自定义字段值的帖子数量。因此,列表如下所示:对于每个:自定义分类名称/帖子数量/此分类中包含具有特定值的自定义帖子字段(键)的帖子数量

到目前为止,我所能做的就是列出自定义分类法和帖子数量(只需列出类别或通过wp数据库查询),或者列出带有特定meta\\u值的帖子作为meta\\u键。但我无法将两者结合起来:

对于自定义分类列表和post计数:

 $variable = wp_list_categories(\'taxonomy=organy&echo=0&show_count=1&title_li=&\');
$variable = preg_replace(\'~\\((\\d+)\\)(?=\\s*+<)~\', \'<span class="rank-nbr">$1</span>\', $variable);
echo $variable;
对于自定义字段的值post count:

$status_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_value = \'fixed\';");
echo \'<p>number of posts: \' . $status_count . \'</p>\';
我想应该通过wpdb查询来完成。

我会感谢更多高级程序员的帮助。。。

我的另一个尝试是:

$terms = get_terms("MY_TAXONOMY_TERM");
$count = count($terms);
$meta_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->postmeta WHERE meta_value = \'MY_SPECIFIC_VALUE\';" );

if ( $count > 0 ){
echo "<tr>";
foreach ( $terms as $term ) {
echo "<td>" . $term->name  ,"</td><td> ",  $term->count . "</td><td> ",  $meta_count, "<td>";

}
echo "</tr>";
}
但这里发生的是具有特定值(MY\\u specific\\u value)的所有帖子的列表。

1 个回复
最合适的回答,由SO网友:gipson 整理而成

The solution is:

global $wpdb;

$terms = get_terms("TAXONOMY_TERM");
$count = count($terms);

if ( $count > 0 ){
foreach ( $terms as $term ) {

$querystr = "

SELECT count(ID) as 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 exists ( SELECT * FROM $wpdb->postmeta WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID) AND meta_key = \'META_KEY\' and meta_value = \'META_VALUE\' )
AND (post_status = \'publish\' )
AND $wpdb->term_taxonomy.taxonomy = \'TAXONOMY_TERM\'
AND $wpdb->term_taxonomy.term_id = \'".$term->term_id."\'
";

$res= $wpdb->get_results($querystr);

echo "<tr><td>" . $term->name  ,"</td><td> ",  $term->count , "</td><td> ",  $res[0]->count, "</td></tr>";
}
}
结束

相关推荐

寄存器_POST_STATUS和SHOW_IN_ADMIN_ALL_LIST

我有一个自定义的帖子状态,它应该是公共可见的,但不显示在编辑屏幕的“所有”列表中。这是我注册帖子状态的方式:register_post_status(\'my_custom_post_status\', array( \'label\' => __(\'The Label\', \'domain\'), \'public\' => true, \'exclude_from_search\' => true, \'show_i