Arif Diggi
Arif Diggi

Reputation: 79

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.

Upvotes: 2

Views: 27627

Answers (2)

Raunak Gupta
Raunak Gupta

Reputation: 10809

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

Upvotes: 10

Rahul Prajapati
Rahul Prajapati

Reputation: 446

The Gallery feature allows wordpress to add one or more image galleries to your posts and pages using a simple Shortcode

[gallery ids="729,732,731,720"]

enter link description here

Upvotes: 0

Related Questions