Search code examples
phpwordpressimageshortcode

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.


Solution

  • // 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!