I’ve got a while loop running that grabs all the posts on my site
while ( $all_query->have_posts() ) : $all_query->the_post();
there is meta data in each on that I need to play with. It’s a field called 'rate' and I need to merge like values, 1-5.
Currently, I’ve got this
while ( $all_query->have_posts() ) : $all_query->the_post();
$fives = 0;
$fours = 0;
$threes = 0;
$twos = 0;
$ones = 0;
if(get_post_meta($post->ID, 'rate', true) == 'five') {
$fives = $fives + 5;
}
if(get_post_meta($post->ID, 'rate', true) == 'four') {
$fours = $fours + 4;
}
if(get_post_meta($post->ID, 'rate', true) == 'three') {
$threes = $threes + 3;
}
if(get_post_meta($post->ID, 'rate', true) == 'two') {
$twos = $twos + 2;
}
if(get_post_meta($post->ID, 'rate', true) == 'one') {
$ones = $ones + 1;
}
endwhile;
it works, but it’s really gross.
Is there a more optimized and clean way to do something like this?
A little bit of array manipulation can greatly simplify this:
The totals are kept inside
$counts, with$counts[1]being the total of ones.$labelsis there to help match the textual representation with the array positions inside$counts— this could of course be done with a plainswitchinstead.The loop uses
array_searchto convert textual representations to array indexes, then simply increments the corresponding count by an amount equal to the index.Production code should of course also account for the possibility of
array_searchreturningfalse.