25% off ProSNIPC25OFF

Display a Custom Field Value via Shortcode

Shortcode [custom_field key="field_name"] outputs the value of any post meta field inline.

PHPby SnipCraft
php
<?php
/**
 * Usage: [custom_field key="my_meta_key"]
 * Optional: [custom_field key="my_meta_key" post_id="42"]
 */
add_shortcode( 'custom_field', 'scseed_custom_field_shortcode' );
function scseed_custom_field_shortcode( $atts ) {
    $atts = shortcode_atts(
        array(
            'key'     => '',
            'post_id' => 0,
        ),
        $atts,
        'custom_field'
    );
    $key     = sanitize_key( $atts['key'] );
    $post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();
    if ( ! $key || ! $post_id ) {
        return '';
    }
    $value = get_post_meta( $post_id, $key, true );
    if ( $value === '' || $value === false ) {
        return '';
    }
    return esc_html( (string) $value );
}
#content#custom-field#display#post-meta#shortcode