Get a custom field value through shortcodes

Creating wordpress short-codes is simple.

add_shortcode('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);
 }
Usage:
 [field "my_key"]
 [field "my_key" post_id=1]
Advertisements

One thought on “Get a custom field value through shortcodes

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s