按meta_key meta_Value发布计数

时间:2011-12-02 作者:Shklyar Sergio

我有100篇帖子(states meta\\u key)和不同的meta\\u值(AK、AR、CA、FL、HW、MN、SC、TX、MN、NJ)。我想在我的站点侧边栏上显示AK-11帖子、AR-9帖子的帖子数量。。。。

3 个回复
SO网友:Johannes Pille
// retrieve all meta_values with key \'state\' from database
$state_posts = $wpdb->get_results("
    SELECT meta_value FROM ".
    $wpdb->prefix."postmeta
    WHERE meta_key = \'state\'
    ORDER BY meta_value ASC",
    ARRAY_A
);

// define counting array
$state_count = array();

// iterate through meta_values, count the occurence of each state
foreach ( $state_posts as $state_post ) {
    if ( isset ( $state_count[$state_post[\'meta_value\']] ) ) {
        $state_count[$state_post[\'meta_value\']] = $state_count[$state_post[\'meta_value\']] + 1;
    } else {
        $state_count[$state_post[\'meta_value\']] = 1;
    }
}

// echo results
echo \'<ul>\';
foreach ( $state_count as $state => $count ) {
     echo \'<li>\' . $state . \': \' . $count . \' posts</li>\';
}
echo \'</ul>\';
SO网友:goldenapples

上面另外两个答案的一个稍微快一点的版本:计算MySQL查询中的帖子数。

$state_query = $wpdb->get_results("
            SELECT meta_value AS state, COUNT(post_id) AS count
            FROM {$wpdb->postmeta} WHERE meta_key = \'state\'
            GROUP BY state ORDER BY state ASC");

if ($state_query) {
    echo \'<ul>\';
    foreach ($state_query as $st) 
        echo \'<li>\' . $st->state . \' - \' . $st->count . \' posts\' . \'</li>\';
    echo \'</ul>\';
}

SO网友:Foxsk8

以下代码确定元值的post计数和post类型。它可以在循环之外使用。

$args = array(
    \'post_type\'  => \'products\',
    \'meta_query\' => array(
        array(
            \'key\'   => \'used\',
            \'value\' => \'new\' 
        )
    )
);
$posts = new WP_Query( $args );
$count = $posts->found_posts; 
echo $count;

结束

相关推荐