Samuel Elh Blog

WordPress, PHP, Python and JavaScript tutorials and snippets

How to display a post snippet with thumbnail, title, excerpt and a read more tag

In this tutorial, we are going to display a snippet of a post we provide its ID, this snippet will show a thumbnail image, post title, 100 characters from post content as excerpt, and a read more link.


Add this to your child-theme‘s functions.php file:

function elh_post_snippet($atts) {
    $a = shortcode_atts( array(
        'id' => 'something'
    ), $atts );
    $atts_id = "{$a['id']}";
    $html = '';
    $id = $atts_id;
    $queried_post = get_post($id);
    $title = $queried_post->post_title;
    $link = get_the_permalink($id);
    $thumb = wp_get_attachment_url( get_post_thumbnail_id($id) );
    $excerpt = strip_tags( substr($queried_post->post_content, 0, 100), ''). '...';
    return <<<HTML
<style type="text/css" media="all">
    .elh-p-snippet {
        max-width: 100%;
    .elh-p-snippet img {
        float: left;
        margin-right: 1em;
    .elh-p-snippet h2 {
        float: left;
        width: 100%;
        margin: 0 0 .5em 0;
    .elh-p-snippet .elh-left,
    .elh-p-snippet .elh-right {
        float: left;
        max-width: 50%;

<div class="elh-p-snippet">
    <div class="elh-left">
        <a href="$link"><img src="$thumb" height="150" width="250" alt="$title" ></a>
    <div class="elh-right">
        <h2><a href="$link">$title</a></h2><br />
        <p>$excerpt<br />
        <a href="$link">Read more</a></p>
add_shortcode('elh-snippet', 'elh_post_snippet');

How to use

Simply add this short-code

[[elh-snippet id=""]]

where you want the snippet to show, like in a widget, post, page etc. and don’t forget to paste a post ID in the shortocde id attribute, like id="1" for the hello world post 🙂

Example, I added this in the following line:

[[elh-snippet id="56"]]
<br />
[[elh-snippet id="18"]]

And here’s what it did:


[elh-snippet id=”56″]
[elh-snippet id=”18″]

Worked for you? wanted to customize it more, or had issues? comment below!

Digital Ocean

Cheap Cloud SSD Hosting

Get a VPS now starting at $5/m, fast and perfect for WordPress and PHP applications

Sign Up with $10 Credit

1 Comment

  1. I think this is the only article on the web which covers all the pieces for displaying a post snippet with thumbnail, title, excerpt and a read more tag.

    But the code has “syntax error, unexpected ‘text’ (T_STRING)”
    around “$html .=”

    If possible, please update the code. THX

Leave a Reply

Your email address will not be published.


© 2018 Samuel Elh - Powered by WordPress, DigitalOcean & NameCheap

Theme by Anders NorenUp ↑

Subscribe to our mailing list

Sign up to receive updates about WordPress, free and premium plugins and themes in general and tips and tricks

* indicates required