How to provide a custom WordPress shortcode

Let’s say you have a client and help them with their WordPress website. If you want to provide them a way to output a certain text or any element on a page consistently you can do that with a shortcode.

What is a shortcode

From a software developers view a shortcode in WordPress can be compared to a function call that returns output that gets rendered into the final web page. And by calling a real PHP function in the background you can basically do whatever you want.

The basic code

Setting up a shortcode can be done in very few lines of code. First, make sure to add your own plugin that holds this code to WordPress and make sure it is activated.

function my_special_shortcode() {
  $result = "My special output!";

  return $result;
}
add_shortcode( 'myshortcode', 'my_special_shortcode' );

You simply declare a function that returns the desired result. Then you register this function with a unique name for the shortcode with the add_shortcode function call.

Attributes with default values

If you want to allow the users of your shortcode to control the output in a certain way you can add attributes to your shortcode function. WordPress comes with a shortcode_atts function that allows you to provide default values for the attributes in case the user does not set them.

function my_special_shortcode2($atts) {
  # Fill in default values
  $atts = shortcode_atts( array(
    'attribute1' => 'Default value 1',
    'attribute2' => 'Default value 2'
  ), $atts, 'myshortcode2' );

  $result = "We have: ".$atts['attribute1']." ".$atts['attribute2'];

  return $result;
}
add_shortcode( 'myshortcode2', 'my_special_shortcode2' );

Conclusion

For more detailed information you should have a look at the WordPress Codex and the Shortcode API pages in particular.