3/31/13 Mastering WordPress Shortcodes | Smashing WordPress wp.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/ 1/53 e.g. JavaScript Go! WordPress Mastering WordPress Shortcodes Introduced in WordPress 2.5, shortcodes are powerful but still yet quite unknown WordPress functions. Imagine you could just type “adsense” to display an AdSense ad or “post_count” to instantly find out the number of posts on your blog. By Jean-Baptiste Jung February 2nd, 2009 Essentials, Shortcodes, Techniques 118 Comments Advertisement
53
Embed
Mastering WordPress Shortcodes - National Council for ... · 3/31/13 Mastering WordPress Shortcodes | Smashing WordPress ... this line after our hello() function, then save and close
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
WordPress shortcodes can do this and more and will definitely make yourblogging life easier. In this article, we’ll show you how to create and useshortcodes, as well as provide killer ready-to-use WordPress shortcodesthat will enhance your blogging experience.
What Are Shortcodes?
Using shortcodes is very easy. To use one, create a new post (or edit anexisting one), switch the editor to HTML mode and type a shortcode inbrackets, such as:
[showcase]
It is also possible to use attributes with shortcodes. A shortcode withattributes would look something like this:
(Smashing’s Note: We are organizing a series of full-day workshopswith some of the most well-respected Web design experts in Freiburg,Germany. Seats are very limited, so grab your workshop ticket today!)
Shortcodes are handled by a set of functions introduced in WordPress 2.5called the Shortcode API. When a post is saved, its content is parsed, andthe shortcode API automatically transforms the shortcodes to perform thefunction they’re intended to perform.
Creating a Simple Shortcode
The thing to remember with shortcodes is that they’re very easy to create. Ifyou know how to write a basic PHP function, then you already know how tocreate a WordPress shortcode. For our first one, let’s create the well-known“Hello, World” message.
1. Open the functions.php file in your theme. If the file doesn’t exists,create it.
2. First, we have to create a function to return the “Hello World” string.Paste this in your functions.php file:
function hello() { return 'Hello, World!';}
3. Now that we have a function, we have to turn it into a shortcode.Thanks to the add_shortcode() function, this is very easy to do. Pastethis line after our hello() function, then save and close thefunctions.php file:
add_shortcode('hw', 'hello');
The first parameter is the shortcode name, and the second is thefunction to be called.
4. Now that the shortcode is created, we can use it in blog posts and onpages. To use it, simply switch the editor to HTML mode and type thefollowing:
As mentioned, shortcodes can be used with attributes, which are veryuseful, for example, for passing arguments to functions. In this example,we’ll show you how to create a shortcode to display a URL, just as youwould with the BBCodes that one uses on forums such as VBulletin andPHPBB.
[hw]
You’re done! Of course, this is a very basic shortcode, but it is a goodexample of how easy it is to create one.
1. Open your functions.php file. Paste the following function in it:
Code explanation. To work properly, our shortcode function must handletwo parameters: $atts and $content. $atts is the shortcode attribute(s). Inthis example, the attribute is called href and contains a link to a URL.$content is the content of the shortcode, embedded between the domainand sub-directory (i.e. between “www.example.com” and “/subdirectory”). Asyou can see from the code, we’ve given default values to $content and$atts.
Now that we know how to create and use shortcodes, let’s look at somekiller ready-to-use shortcodes!
1. Create a “Send to Twitter” Shortcode
The problem. Seems that a lot of you enjoyed the “Send to Twitter” hackfrom my latest article on Smashing Magazine. I also really enjoyed that hack,but it has a drawback: if you paste the code to your single.php file, the“Send to Twitter” link will be visible on every post, which you may not want.It would be better to control this hack and be able to specify when to add itto a post. The solution is simple: a shortcode!
The solution. This shortcode is simple to create. Basically, we just get thecode from the “Send to Twitter” hack and turn it into a PHP function. Pastethe following code in the functions.php file in your theme:
function twitt() { return '<div id="twitit"><a href="http://twitter.com/home?status=Currently reading '.get_permalink($post->ID).'" title="Click to send this page to Twitter!" target="_blank">Share on Twitter</a></div>';}
add_shortcode('twitter', 'twitt');
To use this shortcode, simply switch the editor to HTML mode and thentype:
[twitter]
and a “Send to Twitter” link will appear where you placed the shortcode.
SOUR CE AND R E LATE D PLUG-INS:
2. Create a “Subscribe to RSS” Shortcode
The problem. You already know that a very good way to gain RSSsubscribers is to display a nice-looking box that says something like
“Subscribe to the RSS feed.” But once again, we don’t really want to hard-code something into our theme and lose control of the way it appears. Inthis hack, we’ll create a “Subscribe to RSS” shortcode. Display it in someplaces and not others, in posts or on pages, above or below the maincontent, it’s all up to you.
The solution. As usual, we create a function and then turn it into ashortcode. This code goes into your functions.php file. Don’t forget toreplace the example feed URL with your own!
function subscribeRss() { return '<div class="rss-box"><a href="http://feeds.feedburner.com/wprecipes">Enjoyed this post? Subscribe to my RSS feeds!</a></div>';}
add_shortcode('subscribe', 'subscribeRss');
Styling the box. You probably noticed the rss-box class that was added tothe div element containing the link. This allows you to style the box the wayyou like. Here’s an example of some CSS styles you can apply to your“Subscribe to RSS” box. Simply paste it into the style.css file in your theme:
The problem. Most bloggers use Google AdSense. It is very easy to includeAdSense code in a theme file such as sidebar.php. But successful onlinemarketers know that people click more on ads that are embedded in thecontent itself.
The solution. To embed AdSense anywhere in your posts or pages, create ashortcode:
1. Open the functions.php file in your theme and paste the followingcode. Don’t forget to modify the JavaScript code with your ownAdSense code!
Code explanation. The above code is used simply to display AdSense ads.When the shortcode is inserted in a post, it returns an AdSense ad. It ispretty easy but also, you’ll agree, a real time-saver!
SOUR CE S:
4. Embed an RSS Reader
The problem. Many readers also seemed to enjoy the “8 RSS Hacks forWordPress” post published on Smashing Magazine recently. Now, let’s useour knowledge of both RSS and shortcodes to embed an RSS reader right inour posts and pages.
The solution. As usual, to apply this hack, simply paste the following code inyour theme’s function.php file.
shortcode to display AdSense anywhere on your posts and pages:
[adsense]
Note that our AdSense code is wrapped with an adsense div element,we can style it the way we want in our style.css file.
The feed attribute is the feed URL to embed, and num is the number ofitems to display.
5. Get posts from WordPress Database with a
Shortcode
The problem. Ever wished you could call a list of related posts directly in theWordPress editor? Sure, the “Related posts” plug-in can retrieve relatedposts for you, but with a shortcode you can easily get a list of any number ofposts from a particular category.
The solution. As usual, paste this code in your functions.php file.
function sc_liste($atts, $content = null) { extract(shortcode_atts(array(
To use it, simply paste the following in the WordPress editor, after switchingto HTML mode:
[liste num="3" cat="1"]
This will display a list of three posts from the category with an ID of 1. If youdon’t know how to get the ID of a specific category, an easy way isexplained here.
Code explanation. After it has extracted the arguments and created theglobal variable $posts, the sc_liste() function uses the get_posts()function with the numberposts, order, orderby and category parameters toget the X most recent posts from category Y. Once done, posts areembedded in an unordered HTML list and returned to you.
The problem. In WordPress, images are quite easy to manipulate. But whynot make it even easier? Let’s look at a more complex shortcode, one thatautomatically gets the latest image attached to a post.
The solution. Open the functions.php file and paste the following code:
wp_get_attachment_image() and wp_get_attachment_image_src() WordPressfunctions. Once done, the image is returned and inserted in the postcontent.
SOUR CE S:
7. Adding Shortcodes to Sidebar Widgets
The problem. Even if you enjoyed this article, you may have felt a bitfrustrated because, by default, WordPress doesn’t allow shortcode to beinserted into sidebar widgets. Thankfully, here’s a little trick to enhanceWordPress functionality and allow shortcodes to be used in sidebar widgets.
The solution. One more piece of code to paste in your functions.php file:
add_filter('widget_text', 'do_shortcode');
That’s all you need to allow shortcodes in sidebar widgets!
Code explanation. What we did here is quite simple: we added a filter onthe widget_text() function to execute the do_shortcode() function, whichuses the API to execute the shortcode. Thus, shortcodes are now enabled insidebar widgets.
1. WordPress Shortcode: easily display the last image attached to post
This guest post was written by Jean-Baptiste Jung, a 28-year-old blogger from Belgium, who blogs about Web Developmenton Cats Who Code, about WordPress at WpRecipes and aboutblogging on Cats Who Blog . You can stay in touch with Jeanby following him on Twitter.
Related Articles
10 Useful WordPressHook Hacks
Do-It-Yourself CachingMethods WithWordPress
Creating Mobile-Optimized WebsitesUsing WordPress
Post your job listing in our Job Board!
If you're looking for a job or have a job opening to announce,post it in our job board and get noticed by professionals andwell-respected companies. Submit a job listing, and good luck!
Great tutorial. The one on inserting the adsense will definitely be of greatuse to me.
Excellent article. Clear, consice and easy to follow…exactly what the Drordered :-) Well done!
I’ve already discovered the power of the functions.php-file and theseshortcodes are another tool in my kit, thanks very much !
Wow, that’s great! Didn’t knew that feature existed. I really like the EmbedAdsense Code in posts shortcode. It sure saves a lot of time… Thanks forsharing!
I was lately thinking about how to easily add images with lighboxes toposts… you just hit the jackpot… thanks for the amazing article :)
Good stuff here – I just converted my site to use WordPress, and thisfunctionality seems to offer a great amount of flexibility. I wasn’t awarethat this existed at all, thanks!
great article, definitely going to come in handy
Awesome. i love the twitter shortcode. highly useful…
very helpful article for webmaster who are using wordpress . Very Verythank you.
really awesome article. thanks for sharing
so powerful tips.
Great post. I like a lot of functionality but tons of plugins slow downloading. This one tip replaces several plugins and gives me a greatdirection to go in.
I too noticed this, it’s definitely a bug because it seems to display thecomment box and any related comments for the last post shown. Thishappens on all post types (posts, pages and CTP’s). I would also knowhow to fix this.
Excellent Article !!!!!!
Tabea…. Salam kenal dari Manado – Indonesia. Good n thanks,-
Thanks , this is awesome , made my life 10 years longer ;)
Thanks for the valuable article on shortcodes. Your introduction andapplication of this very powerful WordPress tool has come in handy onseveral occasions throughout my “apprenticeship” with WordPress.
all the shortcodes i define myself end up giving me triplicate results on mypages
for example if i create an adsense short code and embed it in my blog i get3 adsense blocks… but if i use a short code defined in one of the pluginsi’m using it works great (only 1 instance of the results)…
Would you happen to have any insight on this issue ?
Has any had a problem with Shortcode duplicating on pages? I’ve recentlyused a few shortcodes for different wordpress plugins but when I look atthe page i create the code repeats it’s self and I wind up having the 3 ofthe same thing on my page. How do I stop that from happening?
there is a mistake in your post pulling shortcode. it should read list and notliste.
i have used this code on my website
is it possible to pull more than just the title?
Thanks for this wonderful tutorial! I am going to implement it in my client’swebsite right now.
Interesting to note that in WP 2.9.2 shortcodes only seems to work whenusing the template tag the_content(). Using the function get_the_content()
Wonderful post…! it helped me create a shortcode for my site where I allowdownloads only if registered/logged in
Enjoyed the post – but when I tried the rss shortcode on my arras themewith a yahoo.pipe, nothing shows up.
The pipe does show with the rss sidebar widget. Any suggestions or notedconflicts?
Great stuff – please correct the typo in [liste num="3" cat="1"] – it should be“list” not “liste”. Took me like 25-30ms to check this ;-)
Thanks, Andreas
Nice article – will definitely use these shortcodes. This is off-topic, but isthere a way to allow wp registered users to upload their own avatarwithout using the Gravatar website? Is this website doing that? Thanks
hello i am using the elegant themes framework and i pasted the code inthe functions.php as you said but it has error messages. plz help!!
is it possible to take shortcodes that were created for another template,and then put them into a new template? For instance, say I find a templateI like the shortcodes on, can I take those shortcodes and insert them intoanother template for wordpress?
Thanks
I am totally delighte with strong you blog greatly that warned me Godbless yo
Hai friend,
Its very easy to understand and thanks for this post. keep updating ourknowledge through this types of posts.
I’ve created a . It allows you to pull in a little more
information including the date posted and a description/excerpt andprovides some basic CSS to get you started also. I hope it can helpsomeone out there!
modified version of the RSS feed shortcode that usesfetch_feed() instead of wp_rss()
Wow, this is great! You’re awsome Jean!!
Great article.
My question relates to whether plugins run previous to a plugin I wish touse uses a Shortcode already.
Would this cause a collission and different processing of the shortcodebetween the two?
How could I either detect the other shortcode definition or create somemechanism to avoid collissions completely.
MANY people will create shortcodes that are named the same. [hw], [big],[name] ect seem to come to mind as examples.
thanks for the article.
This has just what I needed to get going thanks.
How hard would it be to create a short code that requires you to use a 2part short code. Example: I would like to avoid the copy/paste method thatI’m using to create a 2 column table set. If I could do [side1]…[/side1] [side2]…[.side2] and have them combine each other into 1 table that would beawesome, but it would only work if they are both used.
http://inertubetv.splendidangst.com/archives/79
That’s the table layouts I have manually created in HTML in the post.
Shortcodes are not working in my WordPress(3.2.1) installation. It just printsthe code itself. Anyone has any idea?
You should add “wp_reset_query();” inbetween line 13 and 14 (before“return $retour;”).
Otherwise you mess with the values (date, categories etc) of the mainpost, they will be overriden by the posts from the shortcode. Dependingon your specific theme, this can have unwanted results, wrong values insidebars, footers, etc.
You probably want to go back to the main loop, and that’s exactly what“wp_reset_query();” does.
Rad. I dislike WordPress slightly less after reading this. We (WP + me) havea love/hate relationship.
thanks a lot.. I was breaking my head from last few hours.. and here I foundthe exact solution.
Amazing post. I love it. Thanks for sharing with us. I hope to see more
Thank you. What a nice explanation of Shortcodes and how they work. Ihad no idea they were so simple to create and implement. You haveinspired me to experiment. Thanks!
Great Man!!!
Now I’m going to create my own shortcode…..
Is there a shortcode for username that you can place on a page? Thiswould be for a Welcome page.
Im wanting to create a photo blog theme, i want to use short codes forinserting images into posts rather than the user just adding images straightto the editor.
What I want to do also is wrap the image inside some custom html, this isjust some divs and spans.
so basically the output looks like:
Description goes here.
I’m guessing the shortcode would look something like:
[img src="path to image"]Image Description[/img]
Then the user can just keep adding this shortcode to the editor over andover:
[img src="path to image"]Me at the beach[/img]
[img src="path to image"]Friends at dinner[/img]
[img src="path to image"]Vacation in New Zealand[/img]
Is that possible with shortcodes?
I found this very difficult. I coded the “twitter” example and it worked well.However when I removed the “twitter” code from the functions file, the“twitter” example hung around like a bad smell. Where does the codereside when this happens. The reverse also occurred. I coded the “Helloworld” example but made some sort of mistake. However even when Icorrected the mistake it could not be made to work. I then codedremove_shortcode(‘hw’) and a corrected version of “Hello world”. It thenworked.
Yay! You've decided to leave a comment. That's fantastic! Please keep in mind thatcomments are moderated and rel="nofollow" is in use. So, please do not use aspammy keyword or a domain as your name, or it will be deleted. Let's have apersonal and meaningful conversation instead. Thanks for dropping by!