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:
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: