Created
September 3, 2019 12:42
-
-
Save Hunter-WebDev/8f0e8ce609c84f43d91cba0b6924d9a3 to your computer and use it in GitHub Desktop.
Get post meta shortcode in WordPress
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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