Custom Field Shortcode
Adds a [field] shortcode that prints the value of a custom field of the current post, so you can show details like a price or a subtitle inside the content.
Opens WPIDE on
Code
add_shortcode( 'field', function ( $atts ) {
$atts = shortcode_atts( array( 'name' => '', 'id' => 0, 'default' => '' ), $atts, 'field' );
$key = sanitize_key( $atts['name'] );
if ( '' === $key || is_protected_meta( $key, 'post' ) ) {
return '';
}
$post_id = $atts['id'] ? absint( $atts['id'] ) : get_the_ID();
if ( ! $post_id || ( ! is_post_publicly_viewable( $post_id ) && ! current_user_can( 'read_post', $post_id ) ) ) {
return '';
}
$value = get_post_meta( $post_id, $key, true );
if ( is_array( $value ) || is_object( $value ) || '' === (string) $value ) {
return esc_html( $atts['default'] );
}
return esc_html( $value );
} );
Notes
Example: [field name="subtitle" default="-"]. Hidden fields whose names start with an underscore are never shown.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.