You’ll need a loop before you get to your sidebar loop to initiate your unique values. You could run the same loop twice, with rewind_posts()
between the two loops ( so you get your original loop, starting from index 0 ).
In your first loop, loop through and add all your values to an array so that the array looks something like this:
Array(
[0] => '7011 Trondheim',
[1] => '7048 Trondheim',
[2] => '7022 Trondheim',
[3] => '7011 Trondheim',
[4] => '7011 Trondheim',
[5] => '7048 Trondheim',
[6] => '7022 Trondheim'
)
Note that it will have duplicate values, which is fine for this case. Next let’s count our values using the PHP function array_count_values()
which will give us the results:
Array
(
[7011 Trondheim] => 3
[7048 Trondheim] => 2
[7022 Trondheim] => 2
)
Now we have a unique array which also has a count of duplicates!
NOTE
I’m not familiar with ACF but I imagine we could do something like this to achieve what we’re trying to do – also not tested:
<?php
$addresses = array();
if( have_posts() ) {
while( have_posts() ){
the_post();
$city = get_field( 'poststed' );
$zip = get_field( 'postnummer' );
if( ! empty( $city ) && ! empty( $zip ) )
$address[] = "{$zip} - {$city}";
}
}
if( ! empty( $addresses ) ) {
$uniqueAddresses = array_count_values( $addresses );
}
rewind_posts(); // Incase needed later.
if( ! empty( $uniqueAddresses ) ) : ?>
<h3>Filter etter postnr:</h3>
<ul>
<?php foreach( $uniqueAddresses as $address => $count ) : // Let's loop through our array
// Let's split our unique address back in to `poststed` and `postnummer`
// $addressArr[0] => postnummer
// $addressArr[1] => poststed
$addressArr = explode( ' - ', $address );
?>
<li><a href="https://wordpress.stackexchange.com/questions/168029/?postnr=<?php echo $addressArr[0]; ?>"><?php echo "{$address}({$count})"; ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>