Wordpress Shortcodes

Written by: John | 30th Jun 2014

Many people use a WordPress plugin to add their own shortcodes to posts, but there is (in my opinion) a far cleaner method to add custom short codes. This can be done by use of the WordPress functions.php file found in your themes directory.

I will give a quick demo of how to create a simple WordPress shortcode to format a page into separate boxes to hold some content.

First:

Open your functions.php file and add the function your shortcode is to preform.

'.$content.'
'; return $output; } ?>

The function above will simply echo the content that is placed between the shortcode open and close tags in a div that can be styled to your liking in the style sheet. But first we need to add the shortcode hook to the functions.php that tells WordPress the name of the shortcode and it’s associated function:

 
add_shortcode("my_box", "my_box");

So the full function now looks like this:

'.$content.'
'; return $output; } add_shortcode("my_box", "my_box"); ?>

In the WordPress text editor you would now use this shortcode like this:

[my_box] Hello World, this is my content! [/my_box]

The resulting HTML would now look like this:

<div class="my_box">Hello World, this is my content!</div>

Related Posts

Code

Swipe close for mobile menu

Using Vanilla JS (ish) to add swipe features to mobile views.
Code

Full Width YouTube Videos

Make YouTube videos take the full width of an element while retaining the 16:9 ratio.
Code

CSS Transitions

Easy copy and paste transition css, to enable transitions to all properties.
Code

Command Line SSH stuff

Some tips and tricks for using the command line to do useful stuff, mainly just a reference for myself.
Code

Handy, dandy WordPress excerpt length function

If you have been using WordPress on multiple projects you must have come up against needing to pull a custom excerpt size? Now there are many ways to do this, eg, you could use this to pull say 80 characters…