Skip to content

Instantly share code, notes, and snippets.

@jeharnum
Last active January 16, 2025 19:04
Show Gist options
  • Save jeharnum/f356e55d66d8d4ef69d93f34015c8d68 to your computer and use it in GitHub Desktop.
Save jeharnum/f356e55d66d8d4ef69d93f34015c8d68 to your computer and use it in GitHub Desktop.
<?php
/**
* WordPress ACF Color Palette
* This pulls the colors from theme.json and adds them to the ACF color picker with fallbacks.
*/
add_action('acf/input/admin_footer', 'json_acf_color_palette');
function json_acf_color_palette() {
// Ensure this runs only in admin and ACF is active
if (!is_admin() || !function_exists('acf_get_field_groups')) {
return;
}
$global_settings = wp_get_global_settings();
// Fallback palette
$theme_colors = [
['color' => '#000000'], // Black
['color' => '#ffffff'], // White
];
// Get colors from theme.json if available
if (isset($global_settings['color']['palette']['theme'])) {
$theme_colors = $global_settings['color']['palette']['theme'];
}
// Remove duplicate colors
$unique_colors = array_unique(array_column($theme_colors, 'color'));
?>
<script type="text/javascript">
(function($) {
acf.add_filter('color_picker_args', function(args, $field) {
// Set a default palette
args.palettes = [
<?php
foreach ($unique_colors as $color) {
echo '\'' . esc_html($color) . '\',';
}
?>
];
/*
// Example: Apply a different palette to a specific field
if ($field.attr('data-name') === 'specific_field_name') {
args.palettes = ['#ff0000', '#00ff00']; // Custom palette for specific field
}
*/
return args;
});
})(jQuery);
</script>
<?php
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment