Making Your First WordPress Shortcode

One of my favorite features of WordPress (as a developer) is shortcodes. I think they’re not super great to hand off to end users, but I find they’re fantastic for both:

  1. Making the output of a function insertable into random places in WordPress posts. This is great as a way to handle dynamic data.
  2. They make it really easy and simple to deterministically run a single function in WordPress and see that function’s output.

If you’ve made shortcodes before, you likely already know the above. If you’ve not, check out the video:

Steps to take to Create Your First Shortcode

And of course, if you prefer, here are the step-by-step things you need to do to make your first shortcode.

  1. Put your shortcode into a piece of content on your WordPress site. (This can be done later, but I like to do it first because it makes me think about what I want to call the shortcode before I write any code.)
  2. Open the plugin (preferred) or theme you want to add a line of PHP that says add_shortcode( 'name_of_shortcode', 'name_of_function').
  3. Declare your function. (If you copied and pasted the above, you’d end up with a function called name_of_function. You probably want a better name though.
  4. return the content you want to replace the shortcode in the body of the function. This bit is important! If you echo what you want to appear (if you’re not doing output buffering) it’ll appear in the wrong part of the post’s body.

Just give me that…shortcode…code!

Here’s some representative code if you want a pure copy and paste experience:

add_shortcode( 'qg_shortcode', 'qg_shortcode' );
function qg_shortcode() {
    return 'hi!';
}

Happy hacking!


Add a Comment

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