WordPress Shortcode Registering shortcode


Example

Shortcode is a small piece of code that can be added into the WordPress editor and will output something different once the page is published or previewed.

Frequently, shortcodes are added to the theme functions.php file, but that's not a good practice as shortcodes are expected to keep working after changing themes. Instead, write a plugin to add this functionality.

The structure for registering shortcode is:

function new_shortcode($atts, $content = null){
    // if parameters are needed in the shortcode
    // parameters can be set to default to something
    extract( shortcode_atts( array(
        'param_one' => 'h1'
    ), $atts ) );
    $shortcode = '<'.$param_one'>'.$content.'</'.$param_one.'>';
    return $shortcode;
}
// this is what registers the shortcode with wordpress
add_shortcode('demo-shortcode','new_shortcode');

Inside the WordPress editor, you can type:

[demo-shortcode param_one="h2"]Demo[/demo-shortcode]
// you don't need to insert param_one into the editor if it has a default value.
// having it in the editor will override the default

Once the page is published, this will turn into

<h2>Demo</h2>