Snippets / HTML
HTML
PHP
Show Any Field from Any Post Including Related Posts
D
Donald McGuinn
·
268 views
·
Updated 2 years ago
This code and shortcode allows you to pull in any field from any post or related post on the site.
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 · 2 lines
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 · 21 lines
Discussion
Ask a question or share how you used this.
Log in
to join the discussion.
No comments yet — be the first.