# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Content](https://wpide.com/library/category/content/)
- Tags: shortcode, custom-fields, meta
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/custom-field-shortcode/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Custom Field Shortcode" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
