Skip to content

Instantly share code, notes, and snippets.

@Hunter-WebDev
Created September 3, 2019 12:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Hunter-WebDev/8f0e8ce609c84f43d91cba0b6924d9a3 to your computer and use it in GitHub Desktop.
Save Hunter-WebDev/8f0e8ce609c84f43d91cba0b6924d9a3 to your computer and use it in GitHub Desktop.
Get post meta shortcode in WordPress
<?php
/**
* Returns post meta
*
* Usage:
* [grab_post_meta id="15" key="meta_key"]
* [grab_post_meta key="meta_key"]
*
* For more information on how to use this shortcode view: https://hunterwebdev.io/blog/create-a-custom-shortcode-to-grab-post-meta
*/
function grab_post_meta_shortcode_fn( $atts ) {
$atts = extract( shortcode_atts( array(
'post_id' => false,
'key' => ''
), $atts ) );
if ( ! $key ) {
return;
}
$post_id = (int)($post_id === false ? get_the_ID() : $post_id);
$data = get_post_meta( $post_id, $key, true );
if ( $data ) {
return '<span class="grab-post-meta-value ' . sanitize_html_class('id-' . $post_id) . ' ' . sanitize_html_class('key-' . $key) . '">'. $data .'</span>';
}
}
add_shortcode( 'grab_post_meta', 'grab_post_meta_shortcode_fn' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment