0

I am getting a list categories names based on which tag is selected in WordPress, the code all works and returns a list of categories but I can't get the code to stop the duplicate category names.

Please see my code below:

<?php
    // Get the categories
    $terms = get_terms( array(
      'taxonomy' => 'category',
      'hide_empty' => 0,
      'parent' => $catparid,
    ) );

    // Loop through them
    foreach($terms as $term) {
    // Get the posts in that category with the required tag
      $args = array(
        'category_name'    => $term->name,
        'tax_query'      => array(
         array(
           'taxonomy'  => 'post_tag',
           'field'     => 'slug',
           'terms'     => $cattagfilter
         )
      )
 );

$posts_array = get_posts( $args );

     foreach ($posts_array as $value) {
        $cattest = $term->name;
        echo '<p><a href="/category/case-stuides/' .$term->slug. '">' .$term->name. '</a></p>';
        }       
      }
                                
?>

See screenshot below which shows exactly what is happening in the list of category names.

enter image description here

I've tried using array_unique but it doesn't work unless I am doing soemthing wrong or putting it in the wrong place, I appreciate any help with this.

1
  • 1
    Why are you looping over posts, when you want to output a list of the categories? Of course this will get you duplicates, as soon as two or more posts are in the same category. foreach ($posts_array as $value) - you are not even accessing any part of $value in the output you are creating inside that loop - so what is that supposed to be good for? Create your list by looping over $terms, and remove fetching posts and the second loop. Commented Apr 8, 2024 at 6:40

1 Answer 1

2

You can use array_unique before getting the items (names), and before foreach

<?php
$items = array("Marketing", "NHS", "Nhs", "Science");

$unique_items = array_map(function($item) {
    return strlen($item) == 3 ? strtoupper($item) : strtolower($item);
}, array_unique(array_map('strtolower', $items)));

$unique_items = array_map('ucfirst', $unique_items);

print_r($unique_items); // ["Marketing", "NHS", "Science"]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.