Post thumbnail as div background by shortcode and special post ID

The following code works well, if its integrated inside the loop and if you need an “img” as result.

/* shortcode for post-thumbnail*/
function post_thumbnail( $atts, $content = null ) {
return '<div id="post_thumbnail">' . get_the_post_thumbnail($post_id, 'thumbnail') . '</div>';
}

add_shortcode("post_thumbnail", "post_thumbnail");

/* Shortcode*/
[post_thumbnail]

But I want to create a shortcode, that show me the post thumbnail as a div background (outside the loop) and I need an option to add an ID (for the post ID). Is that possible?

Read More

Nice would be something like this:

[post_thumbnail id="12"]

Related posts

1 comment

  1. Try this.

    // [post_thumbnail post_id=""]
    function post_thumbnail( $atts ) {
        extract(shortcode_atts( array(
            'post_id' => '',
        ), $atts ));
    
        $post_id = isset( $atts['post_id'] ) ? $atts['post_id'] : '';
    
        return '<div id="post_thumbnail">' . get_the_post_thumbnail($post_id, 'thumbnail') . '</div>';
    }
    add_shortcode( 'post_thumbnail', 'post_thumbnail' );
    

    Reference read: Shortcode API.

    Although, I’d add a check if the thumbnail exists using has_post_thumbnail(), and if it has, output the shortcode.

    EDIT

    As image background you’d need:

    // [post_thumbnail post_id=""]
    function post_thumbnail( $atts ) {
        extract(shortcode_atts( array(
            'post_id' => '',
        ), $atts ));
    
        $post_id = isset( $atts['post_id'] ) ? $atts['post_id'] : '';
    
        if (has_post_thumbnail($post_id)) {
    
            $image_post_out = wp_get_attachment_url( get_post_thumbnail_id($post_id) );
    
            return '<div id="post_thumbnail" style="background:url('. esc_url($image_post_out) .'); background-size:cover; min-height:200px;"></div>';
        }
    }
    add_shortcode( 'post_thumbnail', 'post_thumbnail' );
    

    Notice that you need to set the height of an element to have a container width.

    You could use wp_get_attachment_image_src() to get the height and width of an image, and then set it in the style as the width and height of the container, like this:

    // [post_thumbnail post_id=""]
    function post_thumbnail( $atts ) {
        extract(shortcode_atts( array(
            'post_id' => '',
        ), $atts ));
    
        $post_id = isset( $atts['post_id'] ) ? $atts['post_id'] : '';
    
        if (has_post_thumbnail($post_id)) {
    
            $image_atts = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'thumbnail' );
    
            return '<div id="post_thumbnail" style="background:url('. esc_url($image_atts[0]) .'); width:'.$image_atts[1].'px; height:'.$image_atts[2].'px;"></div>';
        }
    }
    add_shortcode( 'post_thumbnail', 'post_thumbnail' );
    

Comments are closed.