How to do WordPress shortcode?

WordPress shortcode is one of the most useful thing that you can do in WordPress. It helps you to insert piece of code that is hard for a non coding creature. It gives you the ability to insert column or action without using any HTML code.

But sometimes it’s not working. The reason is you don’t have a correct format or you forget some cautions for the right structure.

3 Basic Types of WP shortcode

These are just the basic wordpress shortcodes that a normal web designer encounter. I know there are more advance feature for this, but let’s just focus on the most common. Also, note that the codes below will be placed in functions.php of your active WordPress theme.

1. Inserting a text or HTML using WordPress Shortcode

You have this situation that you need to insert a specific piece of html codes inside a post or page but your client is too afraid to insert HTML inside the editor.

function sliderDivBox() {  
    return '<div class="sliderbox"><div id="slider1"><img src="../dog.jpg" /></div><div id="slider2"><img src="../cat.jpg" /></div></div>';  

add_shortcode('slider', 'sliderDivBox');

Based on the code above, the user will just insert [slider] and the div with class of sliderbox will show in the page. Everytime they need to insert the gallery, its now very easy.

2. Wrapping a group of text or code

You can also wrap content using WordPress shortcode.

function three_column( $atts, $content = null ) {  
    return '<div class="span4">"'.$content.'"</div>';  

add_shortcode("col3", "three_column");

The author can now wrap a paragraph using [col3] .. This is a paragraph… [/col3] inside the text editor.

3. Adding attributes to your shortcode

Yes! you can also add attributes on WordPress shortcodes.

function table_shortcode($atts, $content = null) {  
		"width" => '200',
        "cellspacing" => '5', //default value
		"cellpadding" => '4', //default value
		"class" => 'blueTable', //default value
		"border" => '1' //default value
    ), $atts));  
    return '<table width="'.$width.'" cellspacing="'.$cellspacing.'" cellpadding="'.$cellpadding.'" class="'.$class.'" border="'.$border.'">';  

add_shortcode("table", "table_shortcode");

Let’s have a table with it’s attributes. Now, you can customize it inside your article. And have something like [table width=”500″ cellspacing=”3″ cellpadding=”3″ class=”greenTable” border=”0″]

You can also insert a WordPress shortcode in a widget here’s a tutorial: Allow WordPress Widget to do Shortcode

*Some links may contain affiliate links. I may get small commission from your purchases to fund this website and to avoid annoying ads.