How to get custom field value with shortcode
August 31, 2012
Custom field is a very useful functionality in wordpress. We can use it to show extra information on our blog post or page. I explain about shortcode in my previous post. If you are looking to build the shortcode for custom field, here is the solution:
Put the below code into your functions.php
/*************************/
add_shortcode('custom_field', 'shortcode_field');
function shortcode_field($atts){
extract(shortcode_atts(array(
'post_id' => NULL,
), $atts));
if(!isset($atts[0])) return;
$field = esc_attr($atts[0]);
global $post;
$post_id = (NULL === $post_id) ? $post->ID : $post_id;
return get_post_meta($post_id, $field, true);
}
/*************************/
You can use the below shortcode to show the custom field value.
[custom_field "custom_field_key"]
[custom_field "custom_field_key" post_id=1]