Banner
WordPress Tutorials

For what Shortcodes are useful in WordPress?

For what Shortcodes are useful in WordPress?

Shortcodes are specially formatted pieces of text that can be used to insert dynamic output into your posts, pages, widgets, and other static content areas.

Shortcodes come in three main flavors:

  1. A single shortcode like [myshortcode]
  2. Shortcodes with attributes like [myshortcode id=”1″ type=”text”]
  3. Enclosing shortcodes like [myshortcode id=”1″] … some content here … [/myshortcode]

The basics of creating shortcodes is to define the callback function for your shortcode using the add_shortcode() function. Any attributes are added to an array that is passed to the callback as the first $atts parameter. Any enclosed content is passed to the callback as the second $content parameter.

The next code creates a shortcode called msg and makes use of attributes and enclosed content:

<?php
	/*
		shortcode callback for [msg] shortcode
		Example: [msg type="error"]This is an error message.[/msg]
		Output:
		<div class="message message-error">
		<p>This is an error message.</p>
		</div>
	*/
function sp_msg_shortcode($atts, $content)
	{
		//default attributes
		extract( shortcode_atts( array(
		    'type' => 'information',
		    ), $atts ) );
		$content = do_shortcode($content);
		//allow nested shortcodes
		$r = '<div class="message message-' .
		    $type . '"><p>' . $content . '</p></div>';
		return $r;
	}
add_shortcode('msg', 'sp_msg_shortcode');
?>

Notice that the content you want displayed is returned from the callback function rather than echoed to the output buffer. This is because the shortcode filter is typically run before any content has been pushed to the screen. If there were any echo calls inside this function, the output would show up at the top of the page instead of inline where you want it.

Article written by dudecmsadmin

dudecmsadmin

Hi there! I`m admin of Cmsdude.org community where I share everything from web. Im interested more in webdesign.

Leave a Reply

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

Banner