How to get custom field value with shortcode

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]

Related Posts

from my blog


How To Get Hired as a Remote WordPress Developer in 2025

February 14, 2025

In 2025, with the growing demand for remote development and the constantly evolving web landscape, there are many exciting possibilities to become a remote WordPress developer. You can achieve success...

Hire WordPress Experts: Building Your Online Presence with Confidence

April 10, 2024

WordPress can help you create an online presence that is effective for your company. WordPress is a top-rated content management system. To harness its power, you need WordPress specialists. What...

Why Should Your Hire Freelance Web Developer: The Top Benefits

May 17, 2022

When developing a website or an app, there are two major ways to do it - outsource the job to a web development company or hire a freelancer to get...