0

I can show all value in certain meta key(species1 and species2) by my code below. It shows like this. $species[]contains many kinds of bird species.

Crow Eagle Crane Pigeon...

Now, I like to count every article following bird species, and like to show like this.

Crow 15 Eagle 3 Crane 6 Pigeon 2...

How can I combine counting function in this code?

<?php
$posts = get_posts( array(
    'numberposts'   => -1, 
    'category_name' => 'bird',
    'order'         => 'ASC',
) );
    
if ( $posts ) {
    foreach( $posts as $post ) {
        $species[] = get_post_meta( $post->ID, 'species1', true );
        $species[] = get_post_meta( $post->ID, 'species2', true );
    } 
}

$species = array_unique( array_filter( $species ) );
sort( $species );

foreach ( $species as $specie ) {
    echo $specie;
}
?>

1 Answer 1

1

Use array_count_values() (untested):

<?php
$posts = get_posts( array(
    'numberposts'   => -1, 
    'category_name' => 'bird',
    'order'         => 'ASC',
) );
    
if ( $posts ) {
    foreach( $posts as $post ) {
        $species[] = get_post_meta( $post->ID, 'species1', true );
        $species[] = get_post_meta( $post->ID, 'species2', true );
    } 
}

$species = array_filter( $species );
$counts  = array_count_values( $species );
$species = array_unique( $species );
sort( $species );

foreach ( $species as $specie ) {
    printf( '%s %d ', esc_html( $specie ), $counts[ $specie ] );
}
?>
2
  • Thank you. It works completely.
    – cwhiro
    Nov 15, 2023 at 0:54
  • @cwhiro Can you please mark as the answer then (if you are able)?
    – Caleb
    Nov 15, 2023 at 3:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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