I’ve written a small plugin that spits out html for a button. It works great, except for one thing: If the user doesn’t specify an image, the image appears broken. Is there a way for me to check and see if the user has specified an image, and only print the image code if that’s the case?

Here’s my plugin code:

function button_shortcode($args) {
    return "<a class=\"button\" href=\"" . $args["url"] . "\"><img alt=\"" . $args["bigtext"] . "\" class=\"alignleft\" src=\"" . $args["img"] . "\" /><small>" . $args["smalltext"] . "</small>" . $args["bigtext"] . "</a>";
}
add_shortcode("button", "button_shortcode");

Here’s the shortcode:

[button url="http://www.example.com/" img="/path/to/image.png" smalltext="Smaller Text" bigtext="Bigger Text"]

3 s
3

Okay, I’ve re-written the function so that it does the following:

  • checks that your array values are set before using them. You can’t always be sure they’ll be there.
  • if the image is empty, it returns with an error message. Not sure if this is what you want, but you can just remove it.
  • first creates your image html.
  • then, if there’s a URL specified, it wraps up the image in your link HTML. If not, it’ll just return your image HTML.

Note the way I’ve created your HTML. Breaking and opening strings and escaping quotes etc. is messy and difficult to read. Use single quotes when constructing HTML strings so you can use double-quotes without escaping them.

I’ve also used sprintf() and then substitute each piece I want. Much easier to read, and modify later.

Hope it helps!

function button_shortcode($args) {

    if ( empty( $args['img'] ) ) {
        return 'Error - no image source was specified';
    }

    $sBigText = isset( $args['bigtext'] )? $args['bigtext'] : '';
    $sSmallText = isset( $args['smalltext'] )? $args['smalltext'] : '';

    $sHtmlToReturn = sprintf( '<img alt="https://wordpress.stackexchange.com/questions/143075/%s" class="alignleft" src="https://wordpress.stackexchange.com/questions/143075/%s" /><small>%s</small>%s', $sBigText, $args['img'], $sSmallText, $sBigText );

    if ( !empty( $args['url'] ) ) {
        $sHtmlToReturn = sprintf( '<a class="button" href="https://wordpress.stackexchange.com/questions/143075/%s">%s</a>', $args['url'], $sHtmlToReturn );
    }

    return $sHtmlToReturn;
}

Paul.

Leave a Reply

Your email address will not be published. Required fields are marked *