Shortcode for a link and thumbnail

<?php


// Add Shortcode
function blog_shortcode( $atts ) {

// Attributes
extract( shortcode_atts(
    array(
        'id' => '',
    ), $atts )
);

// Code
if (has_post_thumbnail()) {
    $url = wp_get_attachment_url( get_post_thumbnail_id( $id ) );
}
if ( isset( $id ) ) {
    return '<img src="' . $url . '"/><a href="' . get_permalink( $id ) . '">' . get_the_title( $id ) . '</a>';
}

}
add_shortcode( 'blog', 'blog_shortcode' );


?>

I’m trying to make a shortcode to where I can basically type [blog id=”xxxxxx”] and I’ll get a link and thumbnail. Right now I’m getting the link but the thumbnail isn’t working. I don’t think I fully understand how to get the thumbnail ID to become a url for the < img > tag. Any help will be appreciated.

Related posts

Leave a Reply

1 comment

  1. You are assigning the attachment URL to your $url variable:

    $url = wp_get_attachment_url( get_post_thumbnail_id( $id ) );
    

    then passing that same variable back to wp_get_attachment_url:

    return '<img src="' . wp_get_attachment_url( $url ) . '"/><a href="' . get_permalink( $id ) . '">' . get_the_title( $id ) . '</a>';
    

    You should simply output it instead:

    return '<img src="' .$url . '"/><a href="' . get_permalink( $id ) . '">' . get_the_title( $id ) . '</a>';
    

    EDIT:

    You are missing the post ID from has_post_thumbnail. The following should work.

    <?php
    // Add Shortcode
    function blog_shortcode( $atts ) {
    
    // Attributes
        extract( shortcode_atts(
                        array(
                    'id' => '',
                        ), $atts )
        );
    
    // Code
        $image = '';
        if ( isset( $id ) ) {
            if ( has_post_thumbnail( $id ) ) {
                $url = wp_get_attachment_url( get_post_thumbnail_id( $id ) );
                $image = '<img src="' . $url . '"/>';
            }
            return $image . '<a href="' . get_permalink( $id ) . '">' . get_the_title( $id ) . '</a>';
        }
    }
    
    add_shortcode( 'blog', 'blog_shortcode' );
    ?>