tascam424 Posted December 7, 2015 Share Posted December 7, 2015 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. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/299668-add-separator-to-wordpress-function/ Share on other sites More sharing options...
Solution cyberRobot Posted December 8, 2015 Solution Share Posted December 8, 2015 Since get_the_category() returns an array, you could use implode(). More information can be found here: http://php.net/manual/en/function.implode.php Quote Link to comment https://forums.phpfreaks.com/topic/299668-add-separator-to-wordpress-function/#findComment-1527685 Share on other sites More sharing options...
tascam424 Posted December 8, 2015 Author Share Posted December 8, 2015 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 ! <?php $categories = get_the_category(); $category_names = array(); foreach ($categories as $category) { $category_names[] = $category->cat_name; } echo implode (',', $category_names); ?> Quote Link to comment https://forums.phpfreaks.com/topic/299668-add-separator-to-wordpress-function/#findComment-1527693 Share on other sites More sharing options...
cyberRobot Posted December 8, 2015 Share Posted December 8, 2015 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! Your code looks good to me! Quote Link to comment https://forums.phpfreaks.com/topic/299668-add-separator-to-wordpress-function/#findComment-1527694 Share on other sites More sharing options...
tascam424 Posted December 9, 2015 Author Share Posted December 9, 2015 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 !! Quote Link to comment https://forums.phpfreaks.com/topic/299668-add-separator-to-wordpress-function/#findComment-1527729 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.