W3 Mind Logo
Home » How to create “Shortcode” for a custom field

How to create “Shortcode” for a custom field

First of all you need to add below code to the function.php of your WordPress theme.


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);
}

Now use the below Shortcode inside pages or posts to display custom field value.
Make sure the ID of the Shortcode field below should be same as the name of the custom field.

[field “my-block”]

About Author
Picture of W3Mind

W3Mind

W3Mind focuses on Blogging, Make Money Online, SEO, Business Blogging, Social Media, WordPress, Internet Tools, Web Design and Development.
Give it a Share
Facebook
Twitter
LinkedIn
You May Also Like
How to
START A
BLOG
(step by step)
Load WordPress Sites in as fast as 37ms!