WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to list my posts by a specific custom field. At the same time, for each custom field, I would like to count the number of posts with a specific custom field value. I have a custom field 'shops' with different meta value (for example: 'nike', 'adidas', 'puma',...) and I'd like to have list like this:

nike:6 puma:2 adidas:12

I tried with this but it works only if I put "manually" the value of the custom field 'shops':

$args = array('meta_query' => array( array('key' => 'shops','value' => 'Nike')), 'numberposts' => -1, 'category' => -122, 'meta_key' => 'duedate','meta_value' => date("Ymd"),'meta_compare' => '>=' );
$myposts = get_posts( $args );
echo 'Nike: ' .count($myposts);

How to insert the the custom field value as a variable? thanks in advance for your support.

** UPDATE ****

I create this

<?php $args = array('posts_per_page' => -1,'category' => -122,'meta_key' => 'duedate','meta_value' => date("Ymd"),'meta_compare' => '>=' ); $the_query = new WP_Query($args);?>
<?php if ($the_query->have_posts()) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $series = get_post_meta($post->ID, 'shops', true); ?>

<?php if($series): ?>
        <?php $args1 = array('meta_query' => array( array('key' => 'shops','value' => $series)),'posts_per_page' => -1,'meta_key' => 'duedate','meta_value' => date("Ymd"),'meta_compare' => '>=','order' => 'ASC');?>

         <?php $chapters = new WP_Query($args1); ?> 

            <?php $count = $chapters->post_count; echo $series .': '.$count; ?>
<?php endif; ?>
<?php endwhile;endif; ?>

and it works but it display 'shops' as the number of the number of posts:

nike: 2 puma: 3 nike: 2 adidas: 1 puma: 3 puma: 3

probably something in wrong in the first loop. Could you please help me? Thanks

share|improve this question
it looks like you're using custom fields for something that would be better suited as a taxonomy. – Milo May 15 '13 at 13:59
thanks milo. unfortunately my structure doesn't include taxonomies for the shops – advalue May 16 '13 at 9:31

Your Answer


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

Browse other questions tagged or ask your own question.