Jump to content

Add Separator to Wordpress Function

Recommended Posts

Hi guys, i'm attempting to display Wordpress Categories per Post.


I'm aware of this simple standard method

<?php the_category( ', ' ); ?>.

But i actually just want a list of the categories, unformatted and unlinked to the category itself, actually i just want the category name.


So i am using this method

<?php foreach((get_the_category()) as $category) { echo $category->cat_name . ' '; } ?>

This works perfectly if the post only has 1 category, but in the event of multiple categories, there is no separator. Could anybody assist me in adding a separator which will not append to the last in the list ?


I would be grateful for any assistance but please bare in mind i am a mere novice.



Share this post

Link to post
Share on other sites

Thanks for pointing me in the correct direction .. So i worked out a solution, but baring in mind i am an absolute newb, would you mind telling me if this is the cleanest way to achieve what i want.


It works perfectly !


$categories = get_the_category();
$category_names = array();
      foreach ($categories as $category)
           $category_names[] = $category->cat_name;
           echo implode (',', $category_names); 

Share this post

Link to post
Share on other sites

Sorry I rushed my response. For some reason I thought get_the_category() returned an array of category names...not an array of objects. I'm glad to see you were able to put something together out of that!  :happy-04:


Your code looks good to me!

Share this post

Link to post
Share on other sites

Greatly appreciated ! I'm just learning all this and a point in the right direction is much more valuable than somebody pasting a code snippet. Nice to know i got it right too .. Thanks a lot !!

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.