wordpress shortcode

The content of the posts you compose will go through a series of filtering functions¬† before it is presented to the client. The filter tag is “the_content”. One of the filtering functions is do_shortcode.

add_filter('the_content', 'do_shortcode', 11);

This filter replaces all shortcodes(of the form [shortcode parameter1=’value1′ parameter2=’value2′]) in the post with actual content. There can be multiple wordpress short codes for posts, and multiple instances of a specific short code in a post.

To be able to use a short code in the posts, you should register the short code in a wordpress plugin first. The following code adds a wordpress shortcode in php file of a plugin.

add_shortcode( 'ratings', 'ratings_shortcode' );

This function adds an entry in the global array $shortcode_tags to associate the shortcode tag(‘ratings’) with a function(‘ratings_shortcode’) which will generate actual content to replace the short code in the post.

$shortcode_tags[$tag] = $func;

do_shortcode will find all shortcodes in the post and replace them with actual content as follows.

preg_replace_callback( "/$pattern/s", 'do_shortcode_tag', $content );

Note that although preg_match() only finds one occurrence of the pattern, preg_replace, preg_replace_callback will replace all occurrences of the pattern with the output of the function do_shortcode_tag. For every match, an array(the first element is the whole matched string, the second element is what is matched against the pattern in the first bracket, etc.) is formed and passed as the parameter to the do_shortcode_tag. do_shortcode_tag gets the shortcode tag from the parameter(as the third element) and the shortcode attributes(as the fourth element) , then gets the specific shortcode function stored in $shortcode_tags using the tag, and calls that function to get the actual content. So if you find a wordpress short code not working, you may debug the shortcode function associated to the short code tag. You can get the wordpress shotcode list in the $shortcode_tags array.

Occasionally,  you may need to call your shortcode function directly instead of calling it within the filtering function. You should note that your shortcode function is of the following form:


And $attr is an array containing all possible attributes of the shortcode.



Leave a Reply