Shortcodes is a special tag that lets you add functionality to your posts, pages, widgets, without actually writing any code. A shortcode looks like a piece of text enclosed within square brackets. Some examples are given below.
- [schoolgallery]
- [slider]
- [addvideo]
When you load this blog page in a web browser, WordPress replaces the shortcode and actually displays the content. This eliminates the need for copying and pasting codes from other sites, or repeating a tedious task all over again.
How do I Create A Shortcode?
It is that they are very easy to create Shortcodes. If you know how to write a basic PHP function, then you already know how to create your own WordPress ShortCode.
Let’s see how to add a youtube video to any post using shortcode.
Step1:Create a function
The first thing we need to do is define a function that outputs the actual video code in in your theme’s functions.php file.
function custom_youtube_video_code(){ return '<iframe width="560" height="315" src="https://www.youtube.com/embed/L3R5BzUn8AU" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen></iframe>';
} |
Step2: Add shortcode code
Now we need to hook the function up to a shortcode. Fortunately, WordPress comes in with a simple way to make your own shortcodes.
Here’s the call to set up the shortcode.
add_shortcode( 'addvideo' , ' ); |
The first parameter is the name of the shortcode and the second parameter is the function that will be called. When wordpress see my shortcode [addvideo
], it tells WordPress to replace that with the results of our function
.custom_youtube_video_code
How do I add my Shortcode?
Just add the [addvideo] shortcode in the HTML or Visual views of the Post or Page content editor.
There are many WordPress themes and plguins that offer shortcodes to add different elements to your page like pricing, events, etc into WordPress. You can also create a responsive slider , simple survey form and more in WordPress with just a single line of shortcode.