How To Build A WordPress Shortcode

Need to build a custom WordPress shortcode? All you may need is to register the shortcode and define the output in your WordPress theme’s functions file.

Register and define your shortcode's custom output

To register and build your WordPress shortcode’s output you must define this in your WordPress theme’s functions.php file as per below.

function custom_shortcode( $atts, $content ) {
     $output = '<div>';
     $output .= '<p>' . $content . '</p>';
     $output .= '</div>';
     return $output;

add_shortcode( 'shortcode_tag', 'custom_shortcode' );

Using your custom shortcode

To use the custom shortcode, simply type [shortcode_tag]Your content[/shortcode_tag]. This will wrap “Your content” in <p> tags, surrounded by <div> tags.

Never echo, always concatenate and return

If you’re wondering why your shortcode’s content keeps appearing at the top of the page, remember that you should never use echo in your custom shortcode’s function. You should always return the concatenated variable by using $variable .= ‘HTML’;, appending the variable’s HTML code to the last.

This concatenating assignment operator works similar to $variable = $variable . ‘Next value’;.