Co-Founder of Tradeomics. Interactive Designer & Developer @CJRWinteractive. Husband. Father of a beautiful 3 yr old girl.
@brewernA collection of code, insight, tips & tricks. Mostly on design, jQuery, WordPress, Drupal, Rails, & the occasional random thought.
We are going to create a download button like those seen in my “Plugin Posts”, which uses a short code in the post. Luckily, it is super easy. e.g. [ download href="YourLinkGoesHere" ] (without the spaces)
I used an image as a button, but for this tutorial we are going to use a text link. First thing you want to do is open your functions.php file. Copy & Past the following code and your done!
1 2 3 4 5 6 7 8 9 10 | /* --------------------------------------- CREATE SHORTCODE FOR DOWNLOAD BUTTON --------------------------------------- */ function download_button($atts) { extract(shortcode_atts(array( "href" => 'http://' ), $atts)); return '<a href="'.$href.'">Download</a>'; } add_shortcode('download', 'download_button'); |
So how does it work?
The “download_button” is just a function name I came up with. The variable $atts holds all the attributes of your short code, such as “href”. In the next line of code we extract each element of the array and assign it to a variable name. Then return your html. The last thing to do is to use the WordPress Hook “add_shortcode” to add our function as a short code. We will call this short code “download”.
It is that simple! There is a lot more you can do. For example I have Google Analytics tracking the downloads on my link and I wanted the option to temporarily disable the link. I used the Google Analytics Plugin from Yoast to track the link. Here is my function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | /* --------------------------------------- CREATE SHORTCODE FOR DOWNLOAD BUTTON --------------------------------------- */ function download_button($atts, $disable=false) { extract(shortcode_atts(array( "href" => 'http://', "disable" => 'false', ), $atts)); switch($disable) { case "true": return '<span style="opacity: .2;"><img src="/wp-content/themes/mytheme/images/download.png" alt="Download" /></span>'; break; default: return '<a onclick="javascript:pageTracker._trackPageview(\'/downloads\');" href="'.$href.'"><img src="/wp-content/themes/geekee/images/download.png" alt="Download" /></a>'; break; } } add_shortcode('download', 'download_button'); |