How to create your own WordPress shortcodes

WordPress shortcodes
In version 2.5 WordPress introduced shortcodes. They usually come bundled with plugins, or even themes, and what they do is watch for when you insert something inside square brackets then replace that with some other content. It could be a simple sentence or it could be a massive PHP function, it all depends on what you instructed WordPress to do.

Wordpress created a great shortcode which make processing fast, but wouldn’t it be great to know how to create shortcodes of your own?

In this tutorial of Php Point we will show you step by step creating a Wordpress Shortcodes.

A simple Wordpress shortcode
The shortcode API works very simply: first you need to create a callback function that will run anytime the shortcode is used; then you need to tie that function to a specific shortcode making it ready for use. The code is frequently placed in the functions.php file.


In the below example we want to create a shortcode that will create some output every time we type [content] into the editor. First we need to create the callback function that will return the content (in shortcodes we don’t echo anything, everything is returned):
function shortcode_function() {

  return 'This is a test code to check how wordpress shortcodes work. 
        When corresponding shortcode is written then this function will call and 
        these text will be written. Wordpress shortcodes are very easy of use and
        you can create your own custom shortcodes as many as you want.';
}
Next we need to add this shortcode to WordPress using the add_shortcode function in functions.php file, this function adds the shortcode and also ties it to the function we just created. add_shortcode only takes two arguments, the first one being the name we want this shortcode to have (what we will type between the square brackets) and the second one being the function we want to attach to that shortcode:
add_shortcode('content', 'shortcode_function');
When we write ['content'] in our editor or in some file it will call "shortcode_function" and returned content will be display on that page.

No comments:

Post a Comment