Chapter 7. Other WordPress APIs, Objects, and Helper Functions

In this chapter, we cover several WordPress APIs, objects, and helper functions that aren’t otherwise covered in the rest of the book but are still important pieces of a WordPress developer’s arsenal.

Shortcode API

Shortcodes are specially formatted pieces of text that can be used to insert dynamic output into your posts, pages, widgets, and other static content areas.

Shortcodes come in three main flavors.

  1. A single shortcode like [myshortcode].
  2. Shortcodes with attributes like [myshortcode id="1" type="text"].
  3. Enclosing shortcodes like [myshortcode id="1"] ... some content here ... [/myshortcode].

In Chapter 3, we shared an example of how to use shortcodes to add arbitrary content into a WordPress post or page. In that example, like flavor number one, we simply swapped out the shortcode for our content. You can also add attributes to the shortcode to affect the callback function processing it or wrap some content in an opening and closing shortcode pair to filter some particular content.

The basics of creating shortcodes is to define the callback function for your shortcode using the add_shortcode() function. Any attributes are added to an array that is passed to the callback as the first $atts parameter. Any enclosed content is passed to the callback as the second $content parameter.

The following code creates a shortcode called msg and makes use of attributes and enclosed content:

<?php
/*
 shortcode callback for [msg] ...

Get Building Web Apps with WordPress now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.