Search code examples
wordpressadvanced-custom-fieldswordpress-shortcode

Echo Acf color picker into a shortcode


So am using ACF to make a theme color code to echo it in Emails backgrounds and pages backgrounds, using a simple text field.

What I did is I made this snippet:

add_shortcode( 'bg-color', function() {return'<?php the_field('color-code', 'option'); ?>';} );

To echo the text field as: #ffffff

But instead am getting a php error.

When I try using shortcode plugin, it works like a charm, but when I put it as the color field, it will return the exact name of the shortcode and not the actual color code, so it would look like this: page-bacground: [bg-color], instead of page-bacground: #fffff

I know am doing something wrong in the first shortcode, as its a php withen a php, and thats why there is a syntax error.

I have also tried:

add_shortcode( 'bg-color', function() {return'[acf field="color-code" post_id="options"]';} );

But no luck


Solution

  • You need get_field since it returns the value like so:

    add_shortcode('bg-color', function() {
        return get_field('color-code', 'option');
    });
    
    // PHP 7.4+ one liner for this simple case...
    add_shortcode('bg-color', fn() => get_field('color-code', 'option'));