Table of Content

Shortcode Overview Shortcode Overview

WordPressWordPress WordPress (WordPress.org) is a content management system (CMS) based on PHP and MySQL that is usually used with the MySQL or MariaDB database servers but can also use the SQLite database engine. provide a best way to add the custom content with the help of shortcodes.

If you don’t know about the shortcode then, I recomment you to read the what is shortcode in WordPress.

So, Lets start to create your own custom shortcode:

Create a Shortcode Create a Shortcode

We can create a Shortcode in WordPress with the help of add_shortcode.

See below quick simple example:

Here,

  • We have added new shortcode prefix_sample_shortcode
  • By using function add_shortcode()
  • This shortcode simply return the <h2>Hello World</h2>

To see how it works just copy and paste above code into your child themes functions.php file.

Or

Create a new plugin and add above code as it is.

How to use Shortcode? How to use Shortcode?

After copy and paste above code simly use [prefix_sample_shortcode] into the article.

E.g.

And it looks like below screenshot on frontend


Valid Way of Adding Shortcode Valid Way of Adding Shortcode

Always return the markup of the shortcode insted of using echo or print.

Invalid

Valid:

Also, In Most of the cases; If you have more markup which is hard to return at once? Then you can simply do it by concating the markup or by use PHP buffer ob_start() & ob_get_clean().

See below code snippet which show the use of both:

Con-catting the shortcode markup: Con-catting the shortcode markup:

Using PHP buffer ob_start() and ob_get_clean() Using PHP buffer ob_start() and ob_get_clean()

Conclusion Conclusion

Creating a Shortcode is very easy in WordPress with the help of add_shortcode. And We can easily extend the theme and plugin with the help of shortcodes.

Let’s try it yourself and don’t forget to add comments for any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *