1
<?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.

1 Answer 1

2

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' );
?>
4
  • I changed it to .$url. but it's still not working. It just replaces the wp_get_attachment_url right? Apr 12, 2013 at 19:36
  • Please update your question with your new code
    – vancoder
    Apr 12, 2013 at 19:37
  • It has been updated now with the new code Apr 12, 2013 at 19:42
  • I've updated my answer - give that a shot.
    – vancoder
    Apr 12, 2013 at 19:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.