Extra Color Palette for One Post Type
Adds extra colors to the editor palette only while editing a chosen post type (for example a landing page type), and prints the matching color classes on the front end.
Opens WPIDE on
Code
// Post type that gets the extra colors, and the colors (slug => [name, hex]).
$wpide_pt_palette_type = 'page';
$wpide_pt_palette_colors = array(
'wpide-campaign-red' => array( 'Campaign red', '#dc2626' ),
'wpide-campaign-gold' => array( 'Campaign gold', '#ca8a04' ),
);
add_filter( 'wp_theme_json_data_theme', function ( $theme_json ) use ( $wpide_pt_palette_type, $wpide_pt_palette_colors ) {
if ( ! is_admin() ) {
return $theme_json;
}
// phpcs:disable WordPress.Security.NonceVerification.Recommended
$type = '';
if ( ! empty( $_GET['post_type'] ) ) {
$type = sanitize_key( $_GET['post_type'] );
} elseif ( ! empty( $_GET['post'] ) ) {
$type = (string) get_post_type( absint( $_GET['post'] ) );
} elseif ( isset( $GLOBALS['pagenow'] ) && 'post-new.php' === $GLOBALS['pagenow'] ) {
$type = 'post';
}
// phpcs:enable
if ( $type !== $wpide_pt_palette_type ) {
return $theme_json;
}
$data = $theme_json->get_data();
$palette = isset( $data['settings']['color']['palette'] ) ? (array) $data['settings']['color']['palette'] : array();
$palette = isset( $palette['theme'] ) ? (array) $palette['theme'] : $palette;
foreach ( $wpide_pt_palette_colors as $slug => $color ) {
$palette[] = array( 'slug' => $slug, 'name' => $color[0], 'color' => $color[1] );
}
return $theme_json->update_with( array(
'version' => WP_Theme_JSON::LATEST_SCHEMA,
'settings' => array( 'color' => array( 'palette' => $palette ) ),
) );
} );
add_action( 'wp_enqueue_scripts', function () use ( $wpide_pt_palette_type, $wpide_pt_palette_colors ) {
if ( ! is_singular( $wpide_pt_palette_type ) ) {
return;
}
$css = '';
foreach ( $wpide_pt_palette_colors as $slug => $color ) {
$slug = sanitize_key( $slug );
$hex = sanitize_hex_color( $color[1] );
$css .= ":root{--wp--preset--color--{$slug}:{$hex};}.has-{$slug}-color{color:var(--wp--preset--color--{$slug})!important;}.has-{$slug}-background-color{background-color:var(--wp--preset--color--{$slug})!important;}.has-{$slug}-border-color{border-color:var(--wp--preset--color--{$slug})!important;}";
}
wp_register_style( 'wpide-pt-palette', false, array(), '1.0' );
wp_enqueue_style( 'wpide-pt-palette' );
wp_add_inline_style( 'wpide-pt-palette', $css );
} );
Notes
Set the post type and colors at the top. The theme palette is kept; these colors are added to it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.