WordPress Tips: Add a custom call to action by shortcode

When building WordPress sites, I’ve often been in need of adding a call to action with a striking appearance into the site. Working by myself, that’s really no problem – but when it needs to be added into client-created posts and Pages, it can get to be a hassle — and cause long-term problems.

It’s not really effective or efficient to teach all the intricacies of HTML to every client. If you’ve created a cool CTA format which requires specific HTML you also want to make sure that this is as easy as possible for your client to enter into their post.

The easiest way to do this, in my experience, is by adding a simple shortcode, accessible using the quicktags bar in the WordPress HTML editor. (Since I care about HTML quality, I prefer to either disable the Visual editor or at least strongly discourage it’s use.)

The WordPress API makes it shockingly easy to set all this up.

First, we’ll define our Call to action shortcode:


Short and sweet – the first argument is your shortcode itself — with ‘cta’ defined, you’ll used [cta] as your shortcode. Next, we’ll define the function which will handle the shortcode.

234567891011function my_cta($atts, $content='') {extract(shortcode_atts(array('class'=>'my-cta'), $atts));$output = '';if ( $content != '' ) {$output = "


";}return $output;}

The arguments accepted by the ‘my_cta’ function are the attributes of the shortcode, as assigned in the extracted array and the content enclosed by the shortcode. This particular function is designed to accept one shortcode parameter; and not to output anything if there’s no enclosed body. The usage of the shortcode is like this:

[cta class="buy-now"]Buy my awesome widgets today![/cta]

The output would be:

Buy my awesome widgets today!

Want to add another parameter to the shortcode? It’s easy — just add another value into the array of parameters.

Finally, we want to add the quicktag — so here it is:

151617181920212223242526272829add_action('admin_footer','add_quicktags'); function add_quicktags() { ?>Only two pieces to this code, as well: an action added to the footer of your admin pages, and a function which inserts a new quicktag. Need to add multiple quicktags? Just add each one on a new line – there’s no need to add additional actions or additional scripts.

And here’s the whole thing — you can just drop the entire block of code into your theme’s functions.php file and everything here will be available immediately.

123456789101112131415161718192021222324252627282930add_shortcode('cta','my_cta'); function my_cta($atts, $content='') {extract(shortcode_atts(array('class'=>'my-cta'), $atts));$output = '';if ( $content != '' ) {$output = "


";}return $output;} // Add buttons to html editoradd_action('admin_footer','add_quicktags'); function add_quicktags() { ?>The whole thing is only 30 lines of code – including 9 lines of comments.


Post a Comment