Posted by & filed under 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.

wordpress-custom-fields-inside-custom-fields

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.

function shortcode( $atts ) {
		if($atts['meta']) $key = $atts['meta'];
		if($atts['post_id'] && is_numeric($atts['post_id'])) $post_id = $atts['post_id'];
		$white_list = ['no_deposit_bonus_value'];
		if(!$post_id){
			global $post;
			$post_id = $post->ID;
		}
		if(in_array($key, $white_list))
		{
			//return the meta value.
			return get_post_meta( $post_id, $key, true );
		}

	}
add_shortcode( 'bingo', 'bingo_shortcode');

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.

wordpress-custom-fields-inside-custom-fields-shortcode

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.