PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] Wordpress: How to add commas in this get_the_terms function

 February 12, 2022     php, wordpress     No comments   

Issue

I am using this function:

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    foreach($terms as $term) {
        echo $term->name . ", ";
        unset($term);
    }
}

However I see the terms as term1, term2, term3, (with also a comma at the end), how can I show the terms with commas but without that comma when is not necessary?


Solution

Instead of echoing all the variables during your loop, you should store them all to an array and then use the implode() function to echo them all with the formatting you desire.

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    $output = array();
    foreach($terms as $term) {
        $output[] = $term->name;
        unset($term);
    }
    echo implode(", ", $output)
}

Don't want to use an array or variable? There is another solution. Just check if you are currently on the very last element in the array during your loop.

// Get terms for post
$terms = get_the_terms($post->ID, 'skills');
if($terms != null) {
    end($terms);
    $endKey = key($terms);
    foreach($terms as $key => $term) {
        echo $key != $endKey? $term->name.", " : $term->name;
        unset($term);
    }
}

I added $key to the foreach loop so you can compare against that. You can get the final key of the array by doing end($array) and then using key() to get the actual key.



Answered By - GrumpyCrouton
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing