Hello I am using the below code to output a list of locations where staff work from.
However these locations are printing out like this:
Denmark
Istanbul
London
Miami
New York
Seattle
Singapore
Valparaiso
Denmark
Denmark
Istanbul
Istanbul
London
Istanbul
London
London
London
New York
New York
New York
Seattle
Seattle
Singapore
Singapore
Valparaiso
Valparaiso
I would like to not show duplicates, so only output:
Denmark
Istanbul
London
Miami
New York
Seattle
Singapore
Valparaiso
Denmark
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'staff',
'orderby' => 'date',
'order' => 'ASC',
));
if($posts)
{
echo '<ul>';
foreach($posts as $post)
{
echo '<li class="location"><a href="#">' . get_field('location') . '</a></li>';
}
echo '</ul>';
}
?>
Arnav Joy answers:
please try this
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'staff',
'orderby' => 'date',
'order' => 'ASC',
));
if($posts)
{
foreach($posts as $post)
{
$locations[] = get_field('location');
echo '<li class="location"><a href="#">' . get_field('location') . '</a></li>';
}
$locations = array_unique($locations);
echo '<ul>';
foreach($locations as $location){
echo '<li class="location"><a href="#">' . $location . '</a></li>';
}
echo '</ul>';
}
?>
Ross Gosling comments:
Thank you Arnav, this worked:
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'staff',
'orderby' => 'date',
'order' => 'ASC',
));
if($posts)
{
foreach($posts as $post)
{
$locations[] = get_field('location');
}
$locations = array_unique($locations);
echo '<ul>';
foreach($locations as $location){
echo '<li class="location"><a href="#">' . $location . '</a></li>';
}
echo '</ul>';
}
?>
Sébastien | French WordpressDesigner answers:
<?php
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'staff',
'orderby' => 'date',
'order' => 'ASC',
));
$my_table = array();
if($posts)
{
echo '<ul>';
foreach($posts as $post)
{
$location = get_field('location');
if (in_array($location, $my_table)) {
//nothing
} else {
my_table[] = $location;
echo '<li class="location"><a href="#">' . $location . '</a></li>';
}
}
echo '</ul>';
}
?>
Ross Gosling comments:
Parse error: syntax error, unexpected '['
Sébastien | French WordpressDesigner comments:
just replace my_table[] = $location;
by
$my_table[] = $location;
I forgeted just one $
Navjot Singh answers:
Instead of echoing out the list, just get all fields and put it in an array. Then run array_unique on it and strip the duplicates and then display it.
Rempty answers:
Create an array with the values and use array_unique
$posts = get_posts(array(
'numberposts' => -1,
'post_type' => 'staff',
'orderby' => 'date',
'order' => 'ASC',
));
if($posts){
foreach($posts as $post){
$locations[]=get_field('location');
}
}
$locations=array_unique($locations);
if($locations){
echo '<ul>';
foreach($locations as $location){
echo '<li class="location"><a href="#">' . $location . '</a></li>';
}
echo '</ul>';
}