Tell me more ×
WordPress Answers is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have 100 posts to the ( states meta_key ), and different meta_value (AK,AR,CA,FL,HW,MN,SC,TX,MN,NJ). I want to show the post count on my site sidebar for posts AK-11 posts,AR-9 posts....

share|improve this question
what have you got so far? – ptriek Dec 2 '11 at 17:35
I have no solutions. I searched by Google and all wordpress.stackexchange.com. I ololo:) Help please. – Shklyar Sergio Dec 2 '11 at 18:07

2 Answers

// 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>';
share|improve this answer
This code not work. – Shklyar Sergio Dec 2 '11 at 21:24
@ShklyarSergio Missed the key in first iteration. Ought to work now. Sry. – Johannes Pille Dec 2 '11 at 21:41
It worked. Thank you very much Johannes Pille. – Shklyar Sergio Dec 2 '11 at 21:59

A slightly quicker version of the two other answers above: count the posts in your MySQL query.

$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>';
}
share|improve this answer
Ah yeah. I didn't test it. Forgot the GROUP BY clause. I'll update my answer. – goldenapples Dec 2 '11 at 21:43
+1 Concise. @goldenapples – Johannes Pille Dec 2 '11 at 21:47
This code also works. Thank you very much goldenapples. – Shklyar Sergio Dec 2 '11 at 22:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.