Chapter 7. Working with 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.:
-
A single shortcode like
[myshortcode]
-
Shortcodes with attributes like
[myshortcode id="1" type="text"]
-
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 primary step 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
Get Building Web Apps with WordPress, 2nd Edition 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.