Synchronizing Your ACF Color Picker with Gutenberg Color Classes

Using Advanced Custom Fields to create custom blocks has become part of my day-to-day workflow. It is an invaluable tool to simplifying the block creation process without having to dive in to Javascript. In this post I will discuss a simple way to synchronize your ACF Color Picker fields with the automatically added color classes in the Gutenberg Block Editor.

Here is what we will go over in this post:

Set Custom Color Palette in Gutenberg Block Editor

First, we need to make sure we have defined our color palette for the block editor. Here is the code used in my theme to add my color palette. This code goes in your functions.php or associated function file within your theme.

<?php
// Customize Gutenberg color palette
// Match these colors to the variables set up in /assets/scss/partials/base/variables.scss
add_theme_support( 'editor-color-palette', array(
	array(
		'name'  => __( 'Aqua', CHILD_THEME_SLUG ),
		'slug'  => 'aqua',
		'color'	=> '#21a8af',
	),
	array(
		'name'  => __( 'Purple Dark', CHILD_THEME_SLUG ),
		'slug'  => 'purple-dark',
		'color' => '#632695',
	),
	array(
		'name'  => __( 'Purple Light', CHILD_THEME_SLUG ),
		'slug'  => 'purple-light',
		'color' => '#9e15bf',
     ),
     array(
		'name'  => __( 'Pink', CHILD_THEME_SLUG ),
		'slug'  => 'pink',
		'color' => '#b5267b',
     ),
     array(
		'name'  => __( 'Black', CHILD_THEME_SLUG ),
		'slug'  => 'black',
		'color' => '#1d1d2c',
     ),
     array(
		'name'  => __( 'Grey Light', CHILD_THEME_SLUG ),
		'slug'  => 'grey-light',
		'color' => '#f7f7f7',
     ),
     array(
		'name'  => __( 'White', CHILD_THEME_SLUG ),
		'slug'  => 'white',
		'color' => '#ffffff',
     ),
) );

You’ll want to make sure you add the proper CSS to your theme to ensure your colors display on the front and back end of the site. I won’t go in to too much detail on that here. I suggest checking out this post from Bill Erickson for more info.

Set Color Palette in ACF Color Picker

Next we’ll need to customize the ACF Color Picker field to replace the default colors with the colors from our site colors used above. Below is the code used to modify the ACF Color Palette default colors. This code will also go in your functions.php or associated function file within your theme.

<?php
/**
 * ACF Color Palette
 *
 * Add default color palatte to ACF color picker for branding
 * Match these colors to colors in /functions.php & /assets/scss/partials/base/variables.scss
 *
*/
function wd_acf_color_palette() { ?>
<script type="text/javascript">
(function($) {
     acf.add_filter('color_picker_args', function( args, $field ){
          // add the hexadecimal codes here for the colors you want to appear as swatches
          args.palettes = ['#21a8af', '#632695', '#9e15bf', '#b5267b', '#1d1d2c', '#f7f7f7', '#ffffff']
          // return colors
          return args;
     });
})(jQuery);
</script>
<?php }

You’ll notice the hex codes following args.palettes match the hex codes used in the function that registers the custom Gutenberg Block Editor color palette.

Synchronizing Your ACF Color Picker with Gutenberg Color Classes

Lastly, when creating your custom block with ACF we’ll want to set up a variable that associates the hex code provided by the ACF Color Picker with the appropriate color class. Here is the code that is placed inside the block template used to render your block (for more information on creating a custom block with ACF go here).

<?php
// Get ACF Values from color picker
$wd_acf_color_picker_values = get_field( 'your_custom_field' );

// Set array of color classes (for block editor) and hex codes (from ACF)
$wd_block_colors = [
	 // Change these to match your color class (gutenberg) and hex codes (acf)
     "aqua"         => "#21a8af",
     "purple-dark"  => "#632695",
     "purple-light" => "#9e15bf",
     "pink"         => "#b5267b",
     "black"        => "#1d1d2c",
     "white"        => "#ffffff",
     "grey-light"   => "#f7f7f7",
];

// Loop over colors array and set proper class if background color selection matches value
foreach( $wd_block_colors as $key => $value ) {
     if( $wd_acf_color_picker_values == $value ) {
          $wd_color_class = $key;
     }
}

Let’s break down what is happening above:

Line 2: We are getting the ACF field for the color picker we have set up. You’ll want to change your_custom_field to the field name of your color picker.

Lines 6-15: We are setting an array with a key that matches the Gutenberg color class and a value that matches the appropriate hex code. Make sure your key value matches the slug of the color you defined in your Gutenberg Color Palette and the value matches the appropriate hex code of that color set within your ACF Color Picker.

Lines 18-22: We are looping over the array and checking to see if the $value in the array matches the $wd_acf_color_picker_values and if it does set the $key (which is the color class) as a variable called $wd_color_class.

We now have a variable set with the proper Gutenberg color class based on the value fo the ACF Color Picker.

Using the Color Class in the Custom ACF Block

Now that we have set our variable we can use it anywhere in the block as needed. So if you are using the color picker to set the color of a header you would do something like this:

<h2 class="has-color-<?php echo $wd_color_class; ?>">Header Here</h2>

Now when you change the color of that header using the ACF color picker, it will automatically synchronize with the appropriate color using the color class just as the other default items in the block editor do.

You could use this method for anything within the custom block including background colors, header colors, font colors, etc…

Additionally, you could use this method for as many elements as you need to within your block. Since the array of colors is already set, you could simply loop over it and check as many variables against it as you’d like and set appropriate classes with little extra work.

Note that you’ll need to has has-color-{variable} for colors and has-background-color-{variable} for background colors to remain consistent with how Gutenberg assigns colors and background colors.

Benefits of Using this Method

Before using this method I would go the simpler route of simply echo’ing the hex code to the appropriate element creating inline CSS. While this works fine, I believe the above method is better for a number of reasons:

Consistency

Using this method is consistent with how the Block Editor handles assigning colors. Color classes are used to assign colors and background colors. When you set colors using the color palette within the block editor it adds has-color-{color-here} or has-background-color-{color-here} as a class to the element. We want to mirror that in our custom blocks for consistency.

Backwards Compatibility

In the event that we need to change a color on the site we can easily do it via CSS and it will apply site-wide as the colors are all linked to a class, not an inline hex code. We could then make a simple change to the ACF Color Picker to assign a new hex code and a little alteration the the block template to account for old hex values and we would be all set.

Without this setup, you would need to go through every post/page wherever you used the color picker field and manually update the color.

Hopefully in the future ACF will integrate the “Color Settings” fields that integrate directly with the Gutenberg colors, but for now, this is a good solution to keep things consistent.

About Matt Whiteley

Matt has been building bespoke WordPress websites for over 10 years specializing in the Genesis Framework. He integrates Advanced Custom Fields heavily in all builds, especially with the new Gutenberg Block Editor, allowing clients to easily modify all aspects of the their website with ease.

He works with a wide variety of small businesses and agencies across the country providing development services as well as hosting and maintenance. When he isn't coding he enjoys spending time with his wife and two children, golfing and playing poker.

Reader Interactions

Comments

  1. Nick says

    Hi Matt,
    Thanks for sharing this super useful tip! I’m using the same config on one of my sites (EDD + EDD recurring payments) and I currently need to manually change user status when subscription is cancelled.

    I have a question: my customers receive an email 2 weeks before the automatic renewal of their subscription. Some of them cancel their subscription right away so it doesn’t automatically renews. However, they’re still entitled to use their subscription for 2 more weeks. Does your snippet allows them to continue accessing the site until the anniversary date of their subscription, or does it simply blocks them from the moment they cancel their recurring subscription?

    E.g.: customer purchases 1 year subscription on 1 January 2018. On 16 December 2018 customer receives email telling him subscription will automatically renew on 1 January 2019 unless he cancels renewal. Customer cancels subscription. Will customer be able to use subscription until 1 January 2019, or will access be blocked from 16 December 2018 (when customer canceled)?

    Thanks in advance for your help with this question!

    • Matt Whiteley says

      Hey Nick – are you sure you commented on the correct post? Are you referring to a different post on here? I’m assuming this one: https://whiteleydesigns.com/modify-user-role-easy-digital-downloads-edd-subscription-cancelled/.

      If that is the one in question, it wouldn’t have any affect on their actual access. It simply modifies their user role and I don’t believe that is tied to their access. I believe that is tied to their “status” which changes from “active” to “cancelled” (but they still maintain access in cancelled state. Once their expiration date comes it changes to “expired” and they lose access. None of that is tied to user roles so you should be good.

Leave a Reply

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