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 [swd] that took place on April 2, 2014.
WordPress Shortcodes PowerPoint
We always like to see working, live code, so here are the examples used in the talk:
Shortcode Examples
Here’s a simple code example for a shortcode called [wp] that one would put in the functions.php file of their WordPress Theme.
[pre]
add_shortcode( ‘wp’, ‘wordpress_org_shortcode’ );
function wordpress_org_shortcode( $atts )
{
$output = ‘<a href=”http://wordpress.org” title=”WordPress Site” target=”_blank” >
WordPress.org</a>’;
return $output;
}
[/pre]
Plugins are another way to quickly add shortcodes to a WordPress installation, and it’s independent of the WordPress Theme in use.
[pre]
<?php
/*
Plugin Name: Twitter Feed Shortcode
Plugin URI:
Description: A plugin with a shortcode example.
Version: 1.0
Author: Andre Gagnon
Author URI: https://andregagnon.com
License: GPLv2
*/
add_shortcode( ‘tf’, ‘twitter_feed_shortcode’ );
function twitter_feed_shortcode( $atts )
{
$output = ‘<a href=”http://twitter.com/andygagnon”>My Twitter Feed</a>’;
return $output;
}
?>
[/pre]
In fact, two shortcodes were created for this blog post
- [[swd]], a unenclosing shortcode to generate the link for the [swd].
- [[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.