Tired of whatever silly color I've picked? Rotate the overall hue by hovering the site title!

Pulling your color palette from theme.json into ACF color pickers

I'm not sure why ACF doesn't do this by default as it seems like something of a no-brainer. If a given theme has a color palette set, why wouldn't the user want that palette available in each color picker? Seems like an obvious and easy win to me.

The color picker with its default palette replaced.

In any case, it's easy enough to do by tapping into ACF's acf/input/admin_footer hook. Here's what the documentation says about it:

This action is similar to the WordPress admin_footer, except that it is only fired on pages where ACF fields appear ⸺ such as when editing posts, users, taxonomy terms, options pages and front-end forms.

This is a PHP hook, but that's not the only kind ACF offers. It also has a global acf JS object that runs its own filter system. We thus use the PHP hook to get the current theme's theme.json color palette and then the relevant JS hook to modify the arguments passed to its color picker initialization routine.

<?php

add_action('acf/input/admin_footer',function () {
	if (! wp_theme_has_theme_json()) return;

	$colors = wp_get_global_settings(['color', 'palette']);
	$colors = wp_list_pluck($colors['theme'], 'color');

	if (! sizeof($colors)) return;

	?>
	<script>
		(function ($) {
			acf.add_filter('color_picker_args', function (args, field) {
				const colors = <?= json_encode($colors) ?>;

				if (Array.isArray(args.palettes)) {
					args.palettes = args.palettes.concat(colors);
				} else {
					args.palettes = colors;
				}

				return args;
			});
		})(jQuery);
	</script>
	<?php
});

Using a couple relatively new wp_* functions, we can check for a theme.json and then pull data from it using an array-based pathing scheme. We then pluck the color indexes in an manner like array_column() to get a list of color hex codes.

We then "switch" to JS to tap into the color_picker_args filter and get those colors we found into it. After that it's a simple matter of adding them into ACF's color palette. The one shown at the top of the post has twelve colors, which is perhaps too many, so limiting the size of the palette array may be necessary.

Leave a comment

Your email address will not be published. Required fields are marked *