php - Remove duplicates in foreach loop from custom taxonomy
It shows this result in the foreach loop and it should remove any duplicates
spain
philippines
spain
I tried using array_unique() but its not working for me
This is the code I'm using and working fine, its just that it has duplicates
<?php
if (is_tax() || is_category() || is_tag() ){
$qobj = get_queried_object();
$args = array(
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => $qobj->taxonomy,
'field' => 'slug',
'terms' => $qobj->slug
)
)
);
$random_query = new WP_Query( $args );
if ($random_query->have_posts()) {
while ($random_query->have_posts()) {
$random_query->the_post();
$term_list = wp_get_post_terms($post->ID, 'country', array("all"));
foreach($term_list as $term_single) {
echo '<a href="'.dirname(get_the_permalink()).'">';
echo $term_single->slug;
echo '</a><br>';
}
}
}
wp_reset_query();
}
?>
added this for debugging - var_dump($term_list); and this is the result
array (size=1)
0 =>
object(WP_Term)[1464]
public 'term_id' => int 2
public 'name' => string 'Spain' (length=5)
public 'slug' => string 'spain' (length=5)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 2
public 'taxonomy' => string 'country' (length=7)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 2
public 'filter' => string 'raw' (length=3)
array (size=1)
0 =>
object(WP_Term)[1473]
public 'term_id' => int 5
public 'name' => string 'Philippines' (length=11)
public 'slug' => string 'philippines' (length=11)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 5
public 'taxonomy' => string 'country' (length=7)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 2
public 'filter' => string 'raw' (length=3)
array (size=1)
0 =>
object(WP_Term)[1475]
public 'term_id' => int 2
public 'name' => string 'Spain' (length=5)
public 'slug' => string 'spain' (length=5)
public 'term_group' => int 0
public 'term_taxonomy_id' => int 2
public 'taxonomy' => string 'country' (length=7)
public 'description' => string '' (length=0)
public 'parent' => int 0
public 'count' => int 2
public 'filter' => string 'raw' (length=3)
All I need is to remove the duplicates and I am set, I not not very familiar with this and its very complicated, I'm trying to figure this out since yesterday, anybody please help me get it working or just in the right track, thanks
Answer
Solution:
If you keep a list of those already displayed, then before displaying a new one check if it in that list (using
in_array()
). Once displayed, add this into the already displayed list to stop it appearing again...You will need to have...
before the line