Show Any Field from Any Post Including Related Posts

Description/Instructions

This code and shortcode allows you to pull in any field from any post or related post on the site.

If this snippet helped, feel free to buy me a taco :)

Instructions

Use this shortcode in your content. Change it based on your fields and relationship.

[post_meta post_id="123" meta_key="your_custom_field_key"]
[post_meta post_id="@post(post-relation.id)" meta_key="your_custom_field_key"]

  • HTML
Copy Code

function custom_post_meta_shortcode($atts) {
// Shortcode attributes - includes defaults
$atts = shortcode_atts(
array(
'post_id' => 0, // default to current post
'meta_key' => '', // no default key
'single' => true, // whether to return a single value
),
$atts,
'post_meta'
);

// Retrieve post meta
$meta_value = get_post_meta($atts['post_id'], $atts['meta_key'], $atts['single']);

// Return the meta value if it exists, otherwise return an empty string
return $meta_value ? $meta_value : '';
}

// Register the shortcode with WordPress
add_shortcode('post_meta', 'custom_post_meta_shortcode');

  • PHP
Copy Code

Let's Chat About this Snippet