How to build a WordPress shortcode using PHP

How to build a WordPress shortcode using PHP

Shortcodes are a means of running custom PHP code from the WordPress editor. Since you cannot enter PHP directly into the editor, this makes shortcodes very useful.

What can I use a shortcode for?

Shortcodes can be used for a range of purposes from very simple tasks such as HTML formatting, to complex applications such as shopping carts. A common use is to output information relating to the current post or to output a list of posts. For example you could write a shortcode which displays a list of links in a particular format and this shortcode could be added to the WordPress editor on a page, post or custom post type.

Adding the shortcode to my site

You can add your shortcode using the functions.php file that comes with your theme. The format of this is as follows where we are simply using a shortcode to return the admin email address…

function get_admin_email() {
     return get_option( 'admin_email' );
add_shortcode( 'admin_email', 'get_admin_email' );

The convention is to name your PHP function above with a prefix as this will help ensure that your shortcode function name does not already exist within the plugins and theme set up on your site. You would then use this shortcode in the WordPress editor as follows…


Making shortcodes available to widgets

Shortcodes can be added to your text widgets using this handy plugin or if you prefer, by adding the following snippet of code to your functions.php file…

add_filter('widget_text', 'do_shortcode');

Using shortcodes in template files

Shortcodes can be added to your PHP templates using the do_shortcode() function, for example…

echo do_shortcode('[admin_email]');

Submit a Comment

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

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>