Skip to main content

January 4th, 2023

How to Add Colors from theme.json to ACF Color Picker Field

If you’re building block-based themes, odds are your themes are also including a theme.json file to define some style presets for the block editor, including your color palette. What if you want to sync that same palette to the ACF color picker field?

Conceptually working off an approach taken to add custom colors to the color picker field, instead of defining colors manually, theme.json is where we want to look to find them. Settings in theme.json get pulled into the editor so looking at editor settings is a good place to start.

WordPress makes its editor settings accessible in the post editor data module so they can be accessed with:

const $settings = wp.data.select( "core/editor" ).getEditorSettings();
console.log($settings);

If you spit out the variable’s data into the console like above, you’ll see quite a few settings included within it, a chunk of which are populated from theme.json settings. What you’re looking for in this instance is colors. It should be an array of the color palette within your theme.json file, with each color having a name, slug, and color code (color). ACF allows you to add arguments to its color picker via color_picker_args and so we need just the color code for each of these colors found.

The below does this by using the map() method, going through the colors array of data and creating a new array of just the color codes.

function wpfieldwork_acf_input_colors() { ?>

<script type="text/javascript">
(function($) {

  acf.add_filter('color_picker_args', function( $args, $field ){
    
    // this will create a settings variable with all settings
    const $settings = wp.data.select( "core/editor" ).getEditorSettings();

    // pull out the colors from that variable
    let $colors = $settings.colors.map(x => x.color);
    
    // assign those colors to palettes
    $args.palettes = $colors;
    return $args;

  });

})(jQuery);
</script>

<?php }
add_action('acf/input/admin_footer', 'wpfieldwork_acf_input_colors');

This is using the acf/input/admin_footer hook to add some inline JS since it is such a minimal amount required for the functionality. However, if you already are loading some custom JS into your admin in an external file, you could also place this script within that. You can adjust its placement to what makes the most sense to your set up but hopefully this offers insight on how you can access data in the editor settings to reference colors in your theme.json and keep the ACF color palette in sync.

Get the latest in your inbox