skip to Main Content

Very new to WordPress and web design. I have this function for separating categories with a comma ",". But it also adds the comma after the last category. Making it look like this:

Category1, Category2, Category3,

When I want it like this:

Category1, Category2, Category3

Without the last comma behind Category3

How can I stop the function from adding the last comma?

<?php
    $category_detail = get_the_category($post->ID); //$post->ID
    foreach ($category_detail as $cd) {
        echo $cd->cat_name . ', ';
    }
    ?>

Regards

3

Answers


  1. There is many approaches to splitting arrays values.

    Indeed you could achieve it via a foreach loop, by counting iterations.

    $category = get_the_category($post->ID);
    $i = 0;
    foreach ($categories as $category) {
      $i++;
      echo $category->cat_name;
      if ($i < count($items))
        echo ', ';
    };
    

    Tho a more concise approach would be using the implode() native function:

    $categories = get_the_category($post->ID);
    echo implode(', ', $categories);
    
    Login or Signup to reply.
  2. With this foreach loop you are actually converting an array into string. Thus, if it is more understandable to use, you could just erase the last char like this:

    <?php
        $str=''; //single quotes
        $category_detail = get_the_category($post->ID); //$post->ID
        foreach ($category_detail as $cd) {
            $str .= $cd->cat_name . ', ';
        }
    echo substr($str, 0, -1);
        ?>
    
    Login or Signup to reply.
  3. I was being lazy, and searching Google for this, but none of these were quite what I was searching for. I wrote this and will leave it here for anyone else on a similar search.

    Add this to your functions.php:

    function comma_separated_blog_categories( $id, $class = '' )
    {
        // Get the category object
        $categories = get_the_category( $id );
        // Bail if nothing is found
        if ( is_null( $categories ) )
        {
            return;
        }
        // Create an empty array for the output
        $output = array();
        // Loop over the categories
        foreach ( $categories as $category )
        {
            // Category is an object, so grab the name and the id
            $name     = $category->name;
            $url      = get_category_link( $category->ID );
            // Create the output and include our data
            $output[] = '<a href="' . $url . '" class="' . $class . '">' . $name . '</a>';
        }
        // Finally implode the output to apply the comma if it's required...
        return implode( ',', $output );
    }
    

    Then in your templates, echo the function and pass in the post_id and a *class (optional)

    <?php echo comma_separated_blog_categories(get_the_ID(), 'category-item'); ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search