• Posted: 2010-09-27
  • Author: Filip Stefansson
  • Tags:

Add shortcodes

  1.  
  2.  
  3.  
  4.  
  5.  
  6.  
  7.  
  8.  
  9.  
  10.  
  11.  
  12.  
  13.  
  14.  
  15.  
  16.  
  17.  
  18.  
  19.  
  20.  
  21.  
  22.  
  23.  
  24.  
  25.  
  26.  
  27.  
  28.  
  29.  
  30.  
  31.  
  32.  
  33.  
  34.  
<?php
// Simple Shortcode
# Adds a shortcode called 'hello'.
function helloworld() {
  return 'Hello World!';
}
add_shortcode('hello', 'helloworld');  

// Shortcode with parameter
# Adds a shortcode that allows parameters. #
function myname($name) {
 extract(shortcode_atts(array(
  	'name' => 'name'
  	), $name));
  return 'My name is' . $name;
}
add_shortcode('user', 'myname');
# Example: [user name="Filip"] # 

// BB Code style
function font_bold( $attr, $content = null ) {
  return '<span style="font-weight: bold">' . $content . '</span>';
}
add_shortcode('bold', 'font_bold'); 

// BB Code with parameters
function colorpick( $color, $content = null ) {
  extract(shortcode_atts(array(
  	'color' => 'color'
  	), $color));
  return '<span style="color: ' . $color . '">' . $content . '</span>';
}
add_shortcode('font', 'colorpick'); 
?>

Instructions:

As WordPress doesn’t allow code in posts and pages, shortcodes is a good way to implement php-functions in your content.

There are three different kinds of shortcodes:

  • [myshortcode] – Simple shortcode.
  • [myshortcode id="5"] – Shortcode with parameter.
  • [myshortcode]Hello World![/myshortcode] – Shortcode goes BB Code.

Related links:
http://www.smashingmagazine.com/2009/02/02/mastering-wordpress-shortcodes/
http://codex.wordpress.org/Shortcode_API
Share this snippet

If you like this snippet, share it with friends!