Reference:
HOW TO CREATE YOUR OWN WORDPRESS SHORTCODES
BY SARA VIEIRA | JUN. 04, 2013
- In functions.php, create the function:
function lorem_function() {
return 'Lorem ipsum dolor sit amet;
}
- To register the shortcode in functions.php:
add_shortcode('lorem', 'lorem_function');
- To use the shortcode in page editor, enter [lorem] and that’s all.
- For functions with parameters:
function random_picture($atts) {
extract(shortcode_atts(array('width' => 400, 'height' => 200,), $atts));
return '<img src="https://lorempixel.com/'. $width . '/'. $height . '" />';
}
In order to use the attributes we need two functions: the shortcode_atts which is a WordPress function that combines our attributes with known attributes and fills in defaults when needed; and the extract PHP function which, as the name suggests, extracts those attributes we set for our shortcode. Finally the function returns the value we want, in this case the HTML code for our image combined with the width and height variables.
Register: add_shortcode('picture', 'random_picture');
Usage: [picture width="500" height="500"]
Add shortcode to PHP page
Add this line to the php page
<?php echo do_shortcode("[Shortcode]"); ?>
If errors are encountered, try to changing the double quote to single quote.
