Is it possible to link to an array file in add_theme_support( 'editor-color-palette' );

Viewed 108

I'm building a simple color palette plugin that's going to override the gutenburg color settings.

Normally, you can add colors in add_theme_support( 'editor-color-palette' ); in an array like this:

add_theme_support(
    'editor-color-palette',
    [
      [
        'name'  => esc_html__( 'Brown', 'udemy-plugin' ),
        'slug'  => 'brown',
        'color' => '#3a3335',
      ],
      [
        'name'  => esc_html__( 'Orange', 'udemy-plugin' ),
        'slug'  => 'orange',
        'color' => '#f0544f',
      ],
      [
        'name'  => esc_html__( 'Light Green', 'udemy-plugin' ),
        'slug'  => 'light-green',
        'color' => '#c6d8d3',
      ],

    ]
  );

However, I was wondering if it's possible to link the array part to a file? like this:

add_theme_support( 'editor-color-palette', $link-to-array );

If it's possible, how do I link the array file in the plugin? So far, my plugin folder is set up like this:

-Plugin Folder
   -plugin.php (where my code is in)
1 Answers

In WordPress 5.8, theme.json was introduced as a way to better manage custom CSS styles for Gutenberg blocks as an alternative to add_theme_support(). Given your example code, to define and apply a custom colors for a Gutenberg block in the Editor, custom properties and presets in theme.json would be perfect for this.

Eg. json: modified only colors are required for 'editor-color-palette'

[
    {
        "name": "Brown",
        "slug": "brown",
        "color": "#3a3335"
    },
    {
        "name": "Orange",
        "slug": "orange",
        "color": "#f0544f"
    },
    {
         "name": "Light Green",
         "slug": "light-green",
         "color": "#ffffff"
    }
]

The WordPress documentation also has a how-to guide on creating a block-based theme which may help: https://developer.wordpress.org/block-editor/how-to-guides/themes/create-block-theme/

As WordPress and Gutenberg blocks are still be actively developed/updated, always check the official documentation for the latest syntax and up-to-date examples.

UPDATE Here is how to load and decode the theme.json

function wpdc_gutenberg_color_settings() {
...
    $dir = plugin_dir_path( __FILE__ );

    $theme_colors = json_decode(
        file_get_contents( $dir . "theme.json" ), // Returns contents of file as string
        true // Decodes the JSON string into an associative array
    );
add_theme_support('editor-color-palette', $theme_colors );
}
Related