Display post metadata: “title, category, author, date” with shortcode

How to create shortcodes to the standard post-metadata "title, author, category and date" in order to display it in post-content?

E.g. post-content including shorcodes: Lorem ipsum dolor [post_title] sit amet, [post_category] consectetur adipiscing elit [post_author]..

Followed this guide and it worked for the title but can't make it work on the other metadata: category, author name and date. The code is the following:

function myshortcode_title( ){ return get_the_title(); } add_shortcode( 'page_title', 'myshortcode_title' );

Answers 2

  • If you are outside the loop then you can use to get them by post id, you can play around with these snippet:

    shortcode for author's name:

    function author_name_shortcode(){
        global $post;
        $post_id = $post->ID;
        $author = get_the_author($post_id);
        return $author;
    }
    add_shortcode('post_author','author_name_shortcode');
    

    shortcode for categories name:

    function category_name_shortcode(){
        global $post;
        $post_id = $post->ID;
        $catName = "";
        foreach((get_the_category($post_id)) as $category){
            $catName .= $category->name . " ,";
        }
        return $catName;
    }
    add_shortcode('post_category','category_name_shortcode');
    

  • This is usually inside your theme. For post options you can decide which meta data you'd like displayed. If your theme doesn't offer these options then you might consider using a more extensive theme like Genesis


Related Questions