Key Takeaways
Shortcodes in WordPress offer versatile content functionality. Shortcodes enable inserting specialized content easily, enhancing user experience and content management.
Custom shortcodes provide tailored solutions. Creating custom shortcodes allows for unique functionalities, improving content personalization and engagement.
Implementing shortcodes requires basic PHP knowledge. Understanding PHP basics is essential for utilizing and customizing shortcodes effectively.
Optimizing shortcodes enhances content consistency. Centralizing content updates through shortcodes ensures uniformity and efficiency across the website.
If youāve been using WordPress for any length of time, youāve probably already used some shortcodes.
Shortcodes are handy little snippets that let you insert some kind of special functionality into your content that wouldnāt otherwise be possible. As an example: lots of image gallery and slider plugins give you a shortcode that you can simply insert into your content anywhere you like to make the proper images appear there. Shortcodes usually look something like this:
[example shortcode]
In other words: shortcodes cause something special to happen wherever theyāre placed in your text.
But youāre not limited to pre-defined shortcodes; you can define custom shortcodes to do whatever you want! They can be simple, complex, or anything in-between.
In this series, weāll start with a simple shortcode, and work our way up to some more intricate (and even more useful!) examples.
Note: weāll be working mainly with PHP here, specifically in your themeās functions.php file. If you arenāt using a child theme (or a custom/starter theme thatās ok to edit without fear of updates overwriting your changes), youāll want to create a child theme before starting.
Also note: You donāt need any PHP knowledge to go through this post, but knowing at least the basics will help. The code involved here is fairly simple, and weāve tried to make it as easy as possible to copy and customize. Weāll explain each piece of the code as we go, but if youāre completely new to WordPress theme PHP, be aware that a bit of bad code in your functions.php file can break the site.
A Useful Simple Shortcode Example
Letās say we want a shortcode that injects a special author-info section into a post, like this:
Instead of creating and styling the box, image, and text in the WordPress visual editor, weāll just create a shortcode to output that whole thing with a simple snippet!
(Side note: WordPress has better ways of working with author profiles, but weāre sticking with this example because it nicely demonstrates how easy it is to use shortcodes for putting specific blocks of content on a page.)
Step 1: Add the Shortcode in Your Themeās functions.php File
Youāll be using the add_shortcode function to give your shortcode a name, and tell WordPress what it should do any time the shortcode is used. Add this line to your themeās functions.php file:
[php]add_shortcode( 'author_bio', 'create_author_bio' );[/php] It doesnāt really matter where inside functions.php, but to avoid conflicts, Weād recommend putting it at the very end. (If the file ends with a closing ?> tag, though, it should go just before that, not after.)
Before we go any further, letās break that line down a little bit, so that we understand whatās actually going on here. The two bits of text, or āarguments,ā inside the parentheses arenāt special, really; theyāre just names. Letās go over what each one means:
- The first argument: in this case,
author_bioā tells WordPress the actual name of your shortcode. This will be the text that users can type, in brackets, to use the shortcode. So with this code as written,[author_bio]will be our shortcode to trigger our author bio box.
This text could be anything, but itās always best to try to be unique. That way, you wonāt run the risk of your shortcode name conflicting with somebody elseās from another installed plugin or theme. - The second argument: in this case,
create_author_bioā points WordPress toward the actual PHP function it should execute whenever this shortcode is used. Weāll create that function in the next step; for right now, weāre just letting WordPress know what its name is going to be. (This name should also be unique, to avoid conflicts.)
So if it helps, you could think of the code like this:
[php]add_shortcode( 'when_you_see_THIS_shortcode', 'do_THIS' );[/php] If youāre interested in more nitty-gritty detail, check out the add_shortcode Codex entry.
Step 2: Create the Function to Handle the Shortcode
Now we need to actually make the function we just named!
Since we just told WordPress in the last step that the name of our function is create_author_bio, our code should now look like this, once weāve got the new function added:
[php]add_shortcode( 'author_bio', 'create_author_bio' );
function create_author_bio(){
//Code goes here!
}[/php] You may notice this function doesnāt actually do anything yet; all thatās inside of it is a comment. Weāll take care of that in the next step. For now, we just want to point out that there are really only two pieces here: the registration of the shortcode, and the function that happens whenever itās used. WordPress PHP can look intimidating, but itās really that simple!
Side note: it doesnāt matter if the create_author_bio function comes after the add_shortcode function or before it. Order isnāt important in this case.
Step 3: Make the Function do Something
Now all thatās left is to make our function do what we want!
A function like this could do anything, but no matter what, it should eventually return a single value (such as a string of text or a number). That value could be any length or complexity, but whatever the function returns is what will appear wherever our shortcode is used.
For our purposes, this will just be some simple HTML. Hereās the markup to add our author image and bio inside an <aside> element with a custom class (but donāt put this anywhere just yet; weāre just looking at it as a preview for the moment):
[html]
<aside class="author-bio-box">
<img src="https://upload.wikimedia.org/wikipedia/en/1/1f/Bilbo_Baggins_Tolkien_illustration.jpg">
<p>Bilbo Baggins is the author of <cite>The Hobbit</cite>, translator of various works from the elvish, and author of a number of poems and songs.</p>
<p>He is the oldest Hobbit ever in Middle Earth, and spends his days in his Tol Eressƫa home across the sea.</p>
</aside>
[/html] Eventually, weāll use that author-bio-box class on the first line to style the bio with CSS. (Weāll use a class instead of an ID, just in case you want to add more than one author shortcode for content written by multiple authors.) But remember, this could be anything we want to put into the page!
Now, all we need to do is have our shortcodeās function return the above HTML!
Since the functions.php file should only containā¦well, PHP functions (and also for tidiness), Weāve removed the line breaks and spaces between those HTML elements we just looked at and tucked them into a string (inside of single quotes). But functionally, itās still the same HTML snippet we just saw above, and this is how our final PHP code should look:
'<aside class="author-bio-box"><img src="https://upload.wikimedia.org/wikipedia/en/1/1f/Bilbo_Baggins_Tolkien_illustration.jpg"><p>Bilbo Baggins is the author of <cite>The Hobbit</cite>, translator of various works from the elvish, and author of a number of poems and songs.</p><p>He is the oldest Hobbit ever in Middle Earth, and spends his days in his Tol Eressƫa home across the sea.</p></aside>'
Weāre done with PHP! Once weāve saved our functions.php file with the above final code in it, any author can simply enter [author_bio] in any page or post, and the above HTML will appear in the shortcodeās place!
Plus, the really cool thing is: if we ever need to update our bio, we wonāt need to edit every single place it appears! Instead, all we need to do is edit the code in our functions.php file, and it will be updated everywhere all at once. Neat, huh?
However, to make the most out of this, weāll probably want to add some special styling to the bio box.
Step 4: Add Some CSS
The shortcode isnāt great without some styling, so letās add it! You may need to adjust some of the values a little bit, depending on your own siteās fonts (the one in the image above is Fanwood Text) and what CSS rules are already in place. Or you may just want to try something different!
This CSS could be copied into your (child) themeās style.css file, or if youāre running WordPress 4.7 or above (which you should be!), you can just paste this CSS into the āAdditional CSSā box in the Customize screen:
[css].author-bio-box {
background: #d4ead9;
padding: 2em;
overflow: auto;
font-family: Fanwood Text;
font-size: 1.2em;
line-height: 1.4em;
}
.author-bio-box img {
float: left;
max-width: 128px;
height: auto;
margin: 0 1em 0 0;
}
.author-bio-box &amp;amp;amp;gt; p:first-of-type:first-letter {
font-size: 3.1em;
line-height: 1;
float: left;
margin-bottom: -.2em;
}
.author-bio-box &amp;amp;amp;gt; p:last-of-type {
margin: 0;
}[/css] Now things should be looking much better. But feel free to play around with the CSS to make the author box your own and make it feel at home on your site!
Recommended: Make the Function āPluggableā
This isnāt specific to shortcodes, and it isnāt strictly needed for the code to work, but it is best practice, and this is a good time to mention it.
First, a little background on how PHP works:
Remember how we got to name our create_author_bio function ourselves? Well, thereās nothing special about the name create_author_bio; we could have just as easily named our function anything we wanted to (though itās best if the function name gives you at least a little bit of a hint as to what it does, which is why we chose create_author_bio).
But hereās the thing: if two PHP functions are named the same thing, the result will be a fatal error that will prevent the site from loading, since PHP wonāt have any idea which function is the right one. PHP doesnāt guess, so it just stops.
And itās not only our code we need to worry about; a WordPress site might use code from dozens or maybe even hundreds of different developers, depending on the installed plugins and themes. If the same function name is used twice, everything breaks down!
Thatās bad, and obviously, we want to make sure that never happens.
We can do that by making our function āpluggable;ā in other words, telling WordPress not to create our function if another one of the same name already exists. Itās elegantly simple; we just wrap our existing code inside of this easy conditional statement:
[php]if( !function_exists( 'create_author_bio' ) ){
//Our existing PHP goes here!
}[/php] That conditional if expression just checks to be sure that a function named create_author_bio doesnāt already exist. All our PHP code weāve used so far can just be moved inside of that statement, between the { } braces.
Itās still best to name functions as uniquely as possible, though! Making our function pluggable only avoids a fatal error. So if there was a naming conflict, our shortcode still wouldnāt work, but at least the site would still be up and nothing else would be broken.
Conclusion
Thatās it! Hope youāve enjoyed creating a custom author bio shortcode! If youāve followed along, all you need to do is type [author_bio] anywhere in a page or post and your code will appear!
This shortcode can easily be adapted to output anything to a page. A gif, a custom block of HTML and/or JavaScript, an image or videoā¦anything you want!
However, while this example is useful if you just need to output a single, static value onto the page somewhere, itās not very flexible. It will always return the exact same thing every time, and we often need shortcodes to be more adaptable than that.
Good news: weāve only covered the basics of shortcodes, and theyāre capable of much, much more!