Creating simple Shortcodes in WordPress

I’ve built my very own shortcode in WordPress for the first time. Quite the adventure! It’s a very convenient and powerful way to call a function without resorting to writing code while you’re writing text. I needed to echo some text that would rely on something dynamic I wrote in PHP. In my post, all I wrote was [whatever], which would then be replaced by whatever came out of my function.

I didn’t need any parameters to be passed to/from my shortcode, which is fairly easy. Here’s how I did it in principle:

// create your shortcode function
function guru_my_shortcode() {
// do something here
// return text you want to display
return $output;
// register all shortcodes
function guru_shortcodes() {
add_shortcode( 'your-handle', 'guru_my_shortcode' );
add_action( 'init', 'guru_shortcodes' );
view raw shortcodes.php hosted with ❤ by GitHub

We have two little snippets here. The first one is the actual code we want to execute inside our shortcode. Presumably we have some text output, so anything you want printed out should be returned as plain text. WordPress will deal with the actual echoing.

The second snippet will register your function as a shortcode. Give it a handle of your choice with which to call it in [sqaure brackets] from your post. To call this function though, we’ll need to hook it into WordPress in the first place. That’s what we’ll do with the last line of code, which is called in the init hook. I know… it’s complicated. Let me explain in reverse:

  • we register our shortcode by hooking into WordPress init
  • this makes our shortcode available for all users
  • in a post or page, we write [your-handle]
  • as this post is displayed on the front end, our first function is called and text is printed out

There’s a lot more we can do with shortcodes, but I haven’t had a need for it yet. Perhaps in the future. Here’s an article that explains more about it:

Jay is founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or drawing on tablet devices. He blogs about his coding journey at and

You can leave a comment on my original post.