Wordpress: create a custom Shortcode
Following on from my last blog post, this week i decided to create a custom Shortcode utilising the Shortcode API. I needed a Shortcode which wrapped content such as a pages content (this is known as self enclosing) as opposed to a standalone enclosing Shortcode. Check out the Wordpress Codex for more details
In this tutorial, i will show you how to create a Wordpress Shortcode which you can use to wrap around the first letter of a word (useful for adding additonal asthetics to content ) in a Wordpress page.
To create a Shortcode simply use the add_shortcode hook:
Create a handler function:
The handler accepts 2 parameters: one or more Shortcode attributes and the page content to wrap. Inside the function, shortcode_atts() requires 2 attributes:
1) An array of attributes to default to – basically, when the user dosnt bother with attributes in the Shortcode, it will use these. The attributes in this example default to 3 different CSS classes.
2) An array of user defined attributes. If provided, these values will override the default ones.
The code below extracts the Shortcodes attributes for use as variables:
Once extracted, Its best to pass each variable (the key name) into Wordpresses' esc_attr() function to escape user input. Finally, return the content complete with the escaped attributes.
The complete code is below (copy/paste to your themes functions.php file):
Here is some sample CSS for the styles:
Finally heres how to use it (copy/paste into any Wordpress page):