WordPress shortcodes are a way of creating code macros within WordPress post and page content. These simple codes, surrounded by square brackets, can be dropped into text within the WordPress Dashboard editor. Shortcodes provide 2 solutions for web developers:
- DRY (don’t repeat yourself), i.e. write code once and re-use it in WordPress posts and pages. Future updates are in one spot.
- Shield non-tecnhical clients from arcane PHP/HTML code.
Here’s a talk that was created for the Seacoast NH WordPress Developers Meetup that took place on April 2, 2014.
We always like to see working, live code, so here are the examples used in the talk:
Here’s a simple code example for a shortcode called [wp] that one would put in the functions.php file of their WordPress Theme.
add_shortcode( ‘wp’, ‘wordpress_org_shortcode’ );
function wordpress_org_shortcode( $atts )
$output = ‘<a href=”http://wordpress.org” title=”WordPress Site” target=”_blank” >
Plugins are another way to quickly add shortcodes to a WordPress installation, and it’s independent of the WordPress Theme in use.
Plugin Name: Twitter Feed Shortcode
Description: A plugin with a shortcode example.
Author: Andre Gagnon
Author URI: http://andregagnon.com
add_shortcode( ‘tf’, ‘twitter_feed_shortcode’ );
function twitter_feed_shortcode( $atts )
$output = ‘<a href=”http://twitter.com/andygagnon”>My Twitter Feed</a>’;
In fact, two shortcodes were created for this blog post
- [swd], a unenclosing shortcode to generate the link for the Seacoast NH WordPress Developers Meetup.
- [pre], an enclosing shortcode to add a <pre> HTML tag to the code examples.
WordPress shortcodes are a useful code macro tool for creating rich posts and pages that can be easily updated in the future.