Creating simple Shortcodes in WordPress

- by

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:

<?php
// 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:



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.