Shortcode: Get a custom field value through shortcode

Add following snippet to “functions.php”

Usage

[my_custom_field "my_key"]
[my_custom_field "my_key" post_id=1]

Snippet

add_shortcode('my_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);
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>