The What
Description
This construct registers a new shortcode with WordPress’ Shortcode API. Within the content, WordPress will search the text for the shortcode structure, e.g. [shortcode_name]
. Once it finds a possible match, it then compares the name to the registered shortcodes.
If found, the callback runs. That means your code runs to process the request, build the HTML, and then send it back to WordPress.
Your callback will receive three (3) parameters:
- If there are user defined attributes, you will receive them as an array.
- The content found in-between the opening and closing shortcode elements, if applicable.
- The shortcode name.
Parameters
shortcode_name
- The name of shortcode, which is used in the square brackets. For example, an FAQ shortcode would be
[faq]
and theshortcode_name
would befaq
. callback_name
- The fully qualified name of your callback. This is the callback you want to register to this event when it fires.
Return Values
Nothing is returned back from this construct.
Example
add_shortcode( 'faq', 'process_the_faq_shortcode' ); | |
/** | |
* Process the FAQ Shortcode to build a list of FAQs. | |
* | |
* @since 1.0.0 | |
* | |
* @param array|string $user_defined_attributes User defined attributes for this shortcode instance | |
* @param string|null $content Content between the opening and closing shortcode elements | |
* @param string $shortcode_name Name of the shortcode | |
* | |
* @return string | |
*/ | |
function process_the_faq_shortcode( $user_defined_attributes, $content, $shortcode_name ) { | |
$attributes = shortcode_atts( | |
array( | |
'number_of_faqs' => 10, | |
'class' => '', | |
), | |
$user_defined_attributes, | |
$shortcode_name | |
); | |
// do the processing | |
// Call the view file, capture it into the output buffer, and then return it. | |
ob_start(); | |
include( __DIR__ . '/views/faq-shortcode.php' ); | |
return ob_get_clean(); | |
} |