ACF Link Field as a Button
Adds an [acf_button name="cta"] shortcode that renders an ACF link field as a theme-styled button, respecting the "open in new tab" choice.
Opens WPIDE on
Code
add_shortcode( 'acf_button', function ( $atts ) {
$atts = shortcode_atts( array( 'name' => 'cta', 'post_id' => 0 ), $atts, 'acf_button' );
$post_id = $atts['post_id'] ? absint( $atts['post_id'] ) : get_the_ID();
if ( ! $post_id || ! function_exists( 'get_field' ) || ! is_post_publicly_viewable( $post_id ) ) {
return '';
}
$link = get_field( sanitize_key( $atts['name'] ), $post_id );
if ( is_string( $link ) && $link ) {
$link = array( 'url' => $link, 'title' => '', 'target' => '' );
}
if ( ! is_array( $link ) || empty( $link['url'] ) ) {
return '';
}
$title = ! empty( $link['title'] ) ? $link['title'] : 'Learn more';
$target = ! empty( $link['target'] ) ? ' target="_blank" rel="noopener"' : '';
return '<div class="wp-block-button"><a class="wp-block-button__link wp-element-button" href="' . esc_url( $link['url'] ) . '"' . $target . '>' . esc_html( $title ) . '</a></div>';
} );
Notes
Uses the block editor's button classes, so it matches your theme's buttons.
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.