-1

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....

  • 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
5
// 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>';
| 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
3

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>';
}
| 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
  • This code also works. Thank you very much goldenapples. – Shklyar Sergio Dec 2 '11 at 22:20
2

The following code determines the post count of meta value and post type. It can be used outside of the Loop.

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

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