Support » Fixing WordPress » Post Category shortcode

  • shemakeswebsites

    (@shemakeswebsites)


    Hello, I’ve been trying to figure this out for over an hour now and I keep hitting a brick wall.

    I would like to show the current categories of a single post within a shortcode. Is this possible? I was able to display the publish date with a shortcode and figured this would do doable. But with every method I’ve tried, the response on the from end simply says: array

    This is the latest. Any ideas on this? Thank you.

    function shortcode_post_category () {
    return get_the_category();
    }
    add_shortcode( 'post_category', 'shortcode_post_category' ); 
Viewing 3 replies - 1 through 3 (of 3 total)
  • Hi there,

    You’ll find some helpful information in the function reference:

    https://developer.wordpress.org/reference/functions/get_the_category/

    One important thing to know about get_the_category() is it returns an array of objects. So to display the category names in a post you’ll need to loop through that array. Here’s an example:

    function shortcode_post_category () {
    	$html = '';
    	$categories = get_the_category();
    	foreach( $categories as $category ){
    		$html .= '<span>' . $category->name . ' </span>';
    	}
    	return $html;
    }
    add_shortcode( 'post_category', 'shortcode_post_category' );
    shemakeswebsites

    (@shemakeswebsites)

    Thank you, thank you so much. I don’t know how long that would have taken me to figure out!

    I see that the categories have no links. Should they be links to the category archives?

    Yes, you can have links too. You can modify the shortcode function to include links to category archives, or there’s a readymade function that does most of the work for you. get_the_category_list()

    https://developer.wordpress.org/reference/functions/get_the_category_list/

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.