Checking if an attribute exists in a shortcode

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 Comment