The Shortcode API is basically made up of the add_shortcode() function. It’s important to note that functions attached to shortcodes should always return output, not echo. If you’d like to output HTML in a shortcode by escaping from PHP or using echo / print, start with ob_start(); and end with return ob_get_clean();
A shortcode can be executed from PHP using the do_shortcode() function.
Coding Exercise
Go through the add_shortcode() documentation, and create a shortcode with the following requirements:
- The shortcode name should be photos.
- Display random photos from Picsum Photos.
- Shortcode should have height and width attributes.
Ideas to Explore:
- How does WordPress parse the shortcode content?
- What happens in the front end if WordPress is unable to find the shortcode but the shortcode is present in the content?
- How can you escape shortcodes? That is, you want to display the shortcode as it is and not parsed.
- How do you create a custom shortcode in WordPress?
- When you do add_shortcode(), where are the shortcodes stored?
- How can you pass attributes to a shortcode? How are default attributes handled?
- How can you handle nested shortcodes in WordPress?