Outputting Function When Creating a WordPress Shortcode

So I was recently working on a new plugin that involved shortcodes but ran into a bit of a problem when the contents kept getting output at the top of posts/pages before the rest of the content.

Basically this happens because the shortcode is simply returning the data as soon as it’s generated it, not taking note to output it specifically where the user desires. Normally it’s because the content was echoed and not stored and later returned. You can read more about it in this great post but it’s really as simple as that.

However, I was recently faced with this issue and couldn’t figure out why! I was returning the data but it was still being output at the beginning of the post’s content before everything else. I was returning another function (that echoed the content) within my shortcode’s function but it wasn’t helping.

It looked a little bit like this:

https://gist.github.com/bryceadams/b2eef1d659507504f3b9.js

DON’T DO THAT!

What you need to do is run the function through an output buffer with ob_start(); and ob_get_clean();, like so:

https://gist.github.com/bryceadams/7d4a8343b312920c02af.js

And it works! For the PHP nerds, you may be interested why we’re using ob_get_clean(); instead of ob_get_contents(); and ob_clean(); – then check out this discussion.

Change Title of WordPress Meta Boxes

I came across this awesome snippet the other day that I thought I’d share and expand on it a little bit.

When you want to rename the title of a meta box, custom or core, the best way is to remove that meta box and then re-add it with a new title, using something like this:

You’ll need to change the fields above though for:

  • METABOX_ID – eg. commentsdiv. See below for full list.
  • META BOX TITLE – Whatever you’d like to rename the meta box.
  • METABOX_CALLBACK – eg. post_thumbnail_meta_box – See below for full list.
  • POST_TYPE – eg. post, page, etc.

Continue reading

PHP Random String From Array In WordPress

When I struggle to find a clear answer to something and eventually come up with something that works, I like to repost it here so others can hopefully save themselves some time. This is one of those times.

If you want to display a random string from an array in WordPress, such as a random quote from a collection of your favourites, I’m going to show you how. Note that this isn’t a WordPress-specific solution, but I like WordPress and I like when you do too so I’m going to assume you’re using it*.

Continue reading