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

- Type: PHP
- Runs: Run everywhere
- Category: [Custom Post Types & Fields](https://wpide.com/library/category/post-types/)
- Tags: acf, buttons, shortcode
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/acf-link-button-shortcode/

## Code

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

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "ACF Link Field as a Button" 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/
