Displaying Custom Fields within Custom Fields with Shortcodes in WordPress

Or WordPress Meta Inception.

So what if you have your content nicely organised by Meta Boxes, but you sometimes want to reference content from one metabox in another. For example the paragraph in the screenshot below is from a custom field called $review_intro_text. In that field we have included details of a £5 no deposit bonus. It is not uncommon for the value of the bonuses to change every now and again, and when this happens we didn’t want to have to go hunting through our content to find every mention of the bonus amount. We often have text boxes with descriptions that include data we want to keep up to date from a single location.

The solution we decided upon for this was to introduce a new simple shortcode using the shortcode API which would let us display a particular custom field value within another custom field.

This shortcode allows anything in the whitelist to be displayed, it can also be used to reference other posts by throwing in a post id. The shortcode is handy except, by default custom meta text boxes don’t support shortcodes out of the box. So to make this work we just needed to make a small change to our single-bingo-sites.php template to wrap any fields that we’d like to support shortcode with do_shortcode.

echo do_shortcode($review_intro_text);

Then when editing the review we just need to include the shortcode like in the example below.

A word of warning, do_shortcode is fairly resource intensive, so should be used sparingly as if over used will cause performance issues. The only other downside to this is that the shortcodes themselves aren’t that easy to remember so a change we’ll be working on soon is to add a button to the editor that will add the relevant shortcode when it’s clicked.