How to Create Custom Shortcode in WordPress

What is WordPress Shortcode?

Shortcode is a tiny code within “[]”. It lets you show some pre-defined, pre-coded function like a gallery, contact form or some text in post or page body. Even in themes core files. Example, [galleri] [contactform] etc. Since the WordPress 2.5 update, It supports shortcode. The Shortcode API makes it easy to create shortcodes.

How to create custom shortcode in wordpress?

Now it is time to create a shortcode. Here I will show a simple shortcode tutorial. Later, you can extend it with your coding skill.

function mwp_intro($atts){
	return'This is a simple text';
}

add_shortcode('mwp','mwp_intro');

Now add [mwp] anywhere you want to show in post or page.

If you want to show the shortcode in a PHP file. Like if you want to show this shortcode in sidebar.php or footer.php or else, then just add these code.

echo do_shortcode( '[mwp]' );

create custom shortcode in wordpress

Code explanation

In the “mwp_intro” function, you can add PHP codes, HTML, TEXT anything. To learn more, you can check on Shortcode API.

Now, the add_shortcode function will return what you add in the function. In add_shortcode function, the first parameter tells WordPress to create a new shortcode and the second parameter is a callback that hooks to run when the shortcode is found.

Conclusion

In this above tutorial, I have worked with a very easy shortcode. You can write complex function, attributes even you can pass arguments. If you are bothered to create shortcode manually, look for shortcode plugins in WordPress repository.