Output Custom Field Value Within The Content Area Using Shortcode

We all know shortcodes enable you to execute a function and add content within the content area of your editor, as well as other locations. But what if you’re using custom fields and want to output the value of the custom field within the content area?

You can’t use a hook because that only enables you to execute before or after the_content.

What you need to do is combine a function for a shortcode with the function for a custom field.

The 2 functions you need to use are:

add_shortcode and get_post_meta

And here’s an example showing the output of the value of a custom field using a shortcode added manually to the editor, after the first paragraph of content in a post:

front-end

Here’s the Custom Fields meta box in the backend:

custom-field-meta-box

And here’s the shortcode added to the editor after the 1st paragraph of content in the editor:

backend-editor

To make this all happen, you simply need to copy & paste the following PHP code to the end of your child themes functions.php file using a code editor:

function your_shortcode_function() {
	$cf = get_post_meta( get_the_ID(), 'custom_field_name', true );
	$var = '<p class="your-class">' . $cf . '</p>';
	return $var;
}
add_shortcode( 'cfshortcode', 'your_shortcode_function' );

Related Tutorials

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.