Support

Account

Home Forums General Issues Count of posts with the same field choice Reply To: Count of posts with the same field choice

  • @cardosus – I’m very late to the game here, but as this still comes up in Google – here’s a link to the full function in a StackOverflow answer, and also the function below (in case the SO answer also disappears):

    SO Link: https://stackoverflow.com/questions/17741546/count-posts-by-values-from-advanced-custom-field-wordpress

    function get_post_count_by_meta( $meta_key, $meta_value, $post_type) {
    
        $args = array(
            'post_type' => $post_type,
            'numberposts'   => -1,          
            'post_status'   => 'publish',
        );
    
        if ( $meta_key && $meta_value ) {
            if ( is_array($meta_value) ) {
                $args['meta_query'][] = array(
                    'key' => $meta_key,
                    'value' => $meta_value, 
                    'compare' => 'LIKE'
                );
            } else {
                $args['meta_query'][] = array('key' => $meta_key, 'value' => $meta_value);
            }   
        }
    
        $posts = get_posts($args);
        $count = count($posts);
        return $count; 
    
    }
    $post_count = get_post_count_by_meta('test_field', 'Value 1', 'any');
    echo $post_count;