Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WordPress simple Image Shortcode

I am a newbie, please help me with creating a wordpress image shortcode, as simple as:

[img src=""]

Which shows its thumbnail (thumbnail width=100%), links to OR opens the same source image, when clicked.

I tried searching but could not find in existing plugins, please guide me if any.

Please guide me thoroughly for every copy paste in function.php or anywhere else.

like image 610
Arif Diggi Avatar asked Nov 29 '25 14:11

Arif Diggi


1 Answers

// Add Shortcode
function img_shortcode($atts)
{
    // Attributes
    $atts = shortcode_atts(
        [
        'src' => '',
        'link_to_img' => '',
        ], $atts, 'img'
    );

    $return = '';
    if ($atts['link_to_img'] == 'yes')
    {
        $return = '<a href="' . $atts['src'] . '">
                    <img src="' . $atts['src'] . '"/>
                </a>';
    }
    else{
        $return = '<img src="' . $atts['src'] . '"/>';
    }
    // Return HTML code
    return $return;
}

add_shortcode('img', 'img_shortcode');

Code goes in function.php file of your active child theme (or theme). Or also in any plugin php files.

USAGE
Without link:: In PHP

echo do_shortcode('[img src="http://example.com/wp-content/uploads/2017/02/hello.jpg" link_to_img="no"]');

Without link:: In Editor

[img src="http://example.com/wp-content/uploads/2017/02/hello.jpg" link_to_img="no"]

With link:: In PHP

echo do_shortcode('[img src="http://example.com/wp-content/uploads/2017/02/hello.jpg" link_to_img="yes"]');

With link:: In Editor

[img src="http://example.com/wp-content/uploads/2017/02/hello.jpg" link_to_img="yes"]

Hope this helps!

like image 152
Raunak Gupta Avatar answered Dec 02 '25 02:12

Raunak Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!