I have a shortcode that display an image when you use the image url inside it.

function image_code($atts, $content = null) {
    return '<img src="'.$content.'" class="user-imgs"/>';
add_shortcode('img', 'image_code');

So when I use the code like this:


it display only the image like this:(in the css I have set the .user-imgs to max-width 600px)

<img src="https://www.google.com.br/images/srpr/logo3w.png">

But I want to display a link to the full image, like this:

<a href="https://www.google.com.br/images/srpr/logo3w.png"><img src="https://www.google.com.br/images/srpr/logo3w.png">

How I can retrieve the image url used in shortcode and use it as a link in to the original image?


You can reuse the $content parameter:

function image_code($atts, $content = null) {
    $url = esc_url( $content );
    return "<a href='$url'><img src='$url' class='user-imgs' /></a>";

Or pass the URL as parameter in case you want to use a different URL:

function image_code($atts, $content = null) {

    $args = shortcode_atts( array( 'url' => FALSE ), $atts  );
    $img  = esc_url( $content );
    $url  = $args['url'] ? esc_url( $args['url'] ) : $img;

    return "<a href='$url'><img src='$img' class='user-imgs' /></a>";
  • Thank you so much!!! I used the first code, and it worked. Now it returns the correct url! – RogerNobrega Jan 5 '13 at 7:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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