• Resolved Brewinreview

    (@brewinreview)


    Hi all,

    I’m trying to learn how to make shortcodes so I’m starting with an easy one to simply display the title of the most recent post and a short excerpt as seen here.

    So I used the code:

    function new_post_snippet($atts, $content=null){
    
        $getpost = get_posts( array('number' => 1) );
    
        $getpost = $getpost[0];
    
        $return = $getpost->post_title . "<br />" . $getpost->post_excerpt . "…";
    
        $return .= "<br /><a href='" . get_permalink($getpost->ID) . "'><em>read more →</em></a>";
    
        return $return;
    
    }
    add_shortcode('newestpost', 'new_post_snippet');

    Which almost works.

    Everything displays as per the tutorial except for the excerpt…

    What am I missing?

    Cheers

Viewing 4 replies - 1 through 4 (of 4 total)
  • Did you specifically set content for the excerpts when you created the posts? That’s one thing that does trick a lot of people – excepts aren’t created automatically, so unless you set it, it won’t be stored in that field. Functions like get_excerpt() work because if there’s no excerpt set they fall back to getting the first X words form the post body.

    Thread Starter Brewinreview

    (@brewinreview)

    @catacaustic

    No, I didn’t set the excerpt. Makes sense now!

    I just had a play – Caracaustic, do you mean get_the_excerpt – I found that in Google and quickly replacing the $getpost->post_excerpt call with get_the_excerpt() works (kind of).

    It’s currently giving me the first 50 words of the static home page… but it’s a start.

    The only reason that I knew that as fast as I did was that I’ve made the same mistake before… more then once.

    There’s a few functions, and that’s one of them. They all work in similar ways but they all do the same thing and get the excerpt for you. There’s ways to change how many words it gets if you do some searching around.

    Thread Starter Brewinreview

    (@brewinreview)

    Cheers caracaustic.

    I’ll have a further poke around and use one of those functions.

    Thanks again.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘My first shortcode – display recent post’ is closed to new replies.