Display Any ACF Field With a Safe Shortcode
Adds a [field_value name="..."] shortcode that prints an ACF field of the current post and handles images, links, choices, dates and post objects sensibly.
Opens WPIDE on
Code
add_shortcode( 'field_value', function ( $atts ) {
$atts = shortcode_atts( array( 'name' => '', 'post_id' => 0, 'size' => 'medium', 'sep' => ', ' ), $atts, 'field_value' );
$name = sanitize_key( $atts['name'] );
$post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();
if ( '' === $name || ! $post_id || ! function_exists( 'get_field' ) || ! is_post_publicly_viewable( $post_id ) ) {
return '';
}
$value = get_field( $name, $post_id );
$render = function ( $v ) use ( $atts, &$render ) {
if ( $v instanceof WP_Post ) {
return '<a href="' . esc_url( get_permalink( $v ) ) . '">' . esc_html( get_the_title( $v ) ) . '</a>';
}
if ( $v instanceof WP_Term ) {
return '<a href="' . esc_url( get_term_link( $v ) ) . '">' . esc_html( $v->name ) . '</a>';
}
if ( is_array( $v ) ) {
if ( isset( $v['ID'], $v['url'] ) && isset( $v['mime_type'] ) && 0 === strpos( $v['mime_type'], 'image/' ) ) {
return wp_get_attachment_image( (int) $v['ID'], sanitize_key( $atts['size'] ) );
}
if ( isset( $v['url'], $v['title'] ) ) {
$target = ! empty( $v['target'] ) ? ' target="_blank" rel="noopener"' : '';
return '<a href="' . esc_url( $v['url'] ) . '"' . $target . '>' . esc_html( $v['title'] ? $v['title'] : $v['url'] ) . '</a>';
}
if ( isset( $v['label'] ) ) {
return esc_html( $v['label'] );
}
return implode( esc_html( $atts['sep'] ), array_map( $render, $v ) );
}
if ( is_bool( $v ) ) {
return $v ? 'Yes' : 'No';
}
return esc_html( (string) $v );
};
return null === $value || '' === $value || false === $value ? '' : '<span class="field-' . esc_attr( $name ) . '">' . $render( $value ) . '</span>';
} );
Notes
Only fields of public posts are shown. Use post_id="123" for another post and size="medium" for image fields.
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.