PHPackages                             wptrt/control-color-alpha - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. wptrt/control-color-alpha

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

wptrt/control-color-alpha
=========================

Color control for the WordPress Customizer with RGBA support.

v1.1.5(4y ago)39841↓50%1[7 PRs](https://github.com/WPTT/control-color-alpha/pulls)GPL-2.0-or-laterJavaScriptPHP &gt;=5.6

Since Oct 5Pushed 3y ago9 watchersCompare

[ Source](https://github.com/WPTT/control-color-alpha)[ Packagist](https://packagist.org/packages/wptrt/control-color-alpha)[ Docs](https://github.com/WPTRT/control-color-alpha)[ RSS](/packages/wptrt-control-color-alpha/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (7)Dependencies (4)Versions (15)Used By (0)

WPTRT `color-alpha` Control
===========================

[](#wptrt-color-alpha-control)

A color control for the WordPress Customizer with support for alpha channel.

This is a customizer control using the [react-color](https://casesandberg.github.io/react-color/) colorpicker.

The control will save either a HEX value (`#000000`) or RGBA (`rgba(0,0,0,0.9)`) depending on the opacity of the selected color. If the color is completely opaque, then it will save a HEX value. If the selected color is not completely opaque (has an alpha value smaller than 1) then the value will be saved as RGBA.

Usage
-----

[](#usage)

### Registering the Control

[](#registering-the-control)

This is a control containing a JS template. As such, it should be whitelisted in the Customizer. To do that we can use the [`WP_Customize_Manager::register_control_type`](https://developer.wordpress.org/reference/classes/wp_customize_manager/register_control_type/) method:

```
add_action( 'customize_register', function( $wp_customize ) {
	$wp_customize->register_control_type( '\WPTRT\Customize\Control\ColorAlpha' );
} );
```

After we register the control using the above code, we can use it in the customizer using the [Customizer API](https://developer.wordpress.org/themes/customize-api/customizer-objects/):

```
use \WPTRT\Customize\Control\ColorAlpha;

add_action( 'customize_register', function( $wp_customize ) {

	$wp_customize->add_setting( 'your_setting_id' , [
		'default'           => 'rgba(0,0,0,0.5)', // Use any HEX or RGBA value.
		'transport'         => 'refresh',
		'sanitize_callback' => 'my_custom_sanitization_callback'
	] );
	$wp_customize->add_control( new ColorAlpha( $wp_customize, 'your_setting_id', [
		'label'      => __( 'My Color', 'mytheme' ),
		'section'    => 'my_section',
		'settings'   => 'your_setting_id',
	] ) );
} );
```

Available filters
-----------------

[](#available-filters)

### `wptrt_color_picker_alpha_url`

[](#wptrt_color_picker_alpha_url)

You can use this filter to change the URL for control assets. By default the control will work out of the box for any plugins and themes installed in `wp-content/themes` and `wp-content/plugins` respectively. It is possible however to change the URL by using the `wptrt_color_picker_alpha_url` filter:

```
add_filter( 'wptrt_color_picker_alpha_url', function() {
	return get_template_directory_uri() . '/vendor/wptrt/control-color-alpha';
} );
```

Sanitization
------------

[](#sanitization)

All controls in the WordPress Customizer should have a sanitize\_callback defined. You can write your own function and use it as a sanitization callback, or use the example function below:

```
/**
 * Sanitize colors.
 *
 * @since 1.0.0
 * @param string $value The color.
 * @return string
 */
function my_custom_sanitization_callback( $value ) {
	// This pattern will check and match 3/6/8-character hex, rgb, rgba, hsl, & hsla colors.
	$pattern = '/^(\#[\da-f]{3}|\#[\da-f]{6}|\#[\da-f]{8}|rgba\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)(,\s*(0\.\d+|1))\)|hsla\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)(,\s*(0\.\d+|1))\)|rgb\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)|hsl\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)\))$/';
	\preg_match( $pattern, $value, $matches );
	// Return the 1st match found.
	if ( isset( $matches[0] ) ) {
		if ( is_string( $matches[0] ) ) {
			return $matches[0];
		}
		if ( is_array( $matches[0] ) && isset( $matches[0][0] ) ) {
			return $matches[0][0];
		}
	}
	// If no match was found, return an empty string.
	return '';
}
```

Advanced Usage
--------------

[](#advanced-usage)

This control allows you to save the value as either a `string` or an `array`. The default behavior is to save a `string`, but you can easily alter that by using the `choices` argument in the control:

```
$wp_customize->add_control( new ColorAlpha( $wp_customize, 'your_setting_id', [
	'label'    => __( 'My Color', 'mytheme' ),
	'section'  => 'my_section',
	'settings' => 'your_setting_id',
	'choices'  => [
		'save_as' => 'array',
	]
] ) );
```

The value will then be saved using a format like this:

```
[
	'r'    => 107, // Red.
	'g'    => 55, // Green.
	'b'    => 119, // Blue.
	'h'    => 289, // Hue.
	's'    => 37, // Saturation.
	'l'    => 34, // Lightness.
	'a'    => 0.82, // Alpha
	'hex'  => '#6b3777', // The HEX code of the color (alpha = 1)
	'css'  => 'rgba(107,55,119,0.82)', // The CSS value of the selected color.
	'a11y' => [ // An array of accessibility-related properties.
		'luminance'                         => 0.0719,
		// Contrast with white (value 0 - 21).
		'distanceFromWhite'                 => 8.613,
		// Contrast with black (value 0 - 21).
		'distanceFromBlack'                 => 2.438,
		// Maximum contrasting color. Use this to get the text-color
		// if the colorpicker is used to select a background-color.
		'maxContrastColor'                  => '#ffffff',
		// Readable text-colors on white background preserving the hue.
		// The 1st value has a minimum contrast of 7:1 with white.
		// The 2nd value has a minimum contrast of 4.5:1 with white.
		'readableContrastingColorFromWhite' => [ '#6b3777', '#6b3777' ],
		// Readable text-colors on black background preserving the hue.
		// The 1st value has a minimum contrast of 7:1 with black.
		// The 2nd value has a minimum contrast of 4.5:1 with black.
		'readableContrastingColorFromBlack' => [ '#bc83c7', '#a458b5' ],
		// True if the color is dark.
		'isDark'                            => true
	],
]
```

Array Sanitization
------------------

[](#array-sanitization)

If you choose to save the value of this control as an `array`, then you will need to change the sanitization function for this setting. You can write your own, or use the one below.

```
/**
 * Sanitize colors.
 *
 * @since 1.0.0
 * @param array $value The color.
 * @return array
 */
function my_custom_sanitization_callback( $value ) {
	return [
		'r' => (int) $value['r'],
		'g' => (int) $value['g'],
		'b' => (int) $value['b'],
		'h' => (int) $value['h'],
		's' => (int) $value['s'],
		'l' => (int) $value['l'],
		'a' => (float) $value['a'],

		'hex' => my_custom_color_string_sanitization_callback( $value['hex'] ),
		'css' => my_custom_color_string_sanitization_callback( $value['css'] ),

		'a11y' => [
			'luminance'         => (float) $value['a11y']['luminance'],
			'distanceFromWhite' => (float) $value['a11y']['distanceFromWhite'],
			'distanceFromBlack' => (float) $value['a11y']['distanceFromBlack'],
			'maxContrastColor'  => my_custom_color_string_sanitization_callback( $value['a11y']['maxContrastColor'] ),
			'isDark'            => (float) $value['a11y']['isDark'],

			'readableContrastingColorFromWhite' => [
				my_custom_color_string_sanitization_callback( $value['a11y']['readableContrastingColorFromWhite'][0] ),
				my_custom_color_string_sanitization_callback( $value['a11y']['readableContrastingColorFromWhite'][1] ),
			],
			'readableContrastingColorFromBlack' => [
				my_custom_color_string_sanitization_callback( $value['a11y']['readableContrastingColorFromBlack'][0] ),
				my_custom_color_string_sanitization_callback( $value['a11y']['readableContrastingColorFromBlack'][1] ),
			]
		]
	];
}

/**
 * Sanitize colors.
 *
 * @since 1.0.0
 * @param string $value The color.
 * @return string
 */
function my_custom_color_string_sanitization_callback( $value ) {
	// This pattern will check and match 3/6/8-character hex, rgb, rgba, hsl, & hsla colors.
	$pattern = '/^(\#[\da-f]{3}|\#[\da-f]{6}|\#[\da-f]{8}|rgba\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)(,\s*(0\.\d+|1))\)|hsla\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)(,\s*(0\.\d+|1))\)|rgb\(((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*,\s*){2}((\d{1,2}|1\d\d|2([0-4]\d|5[0-5]))\s*)|hsl\(\s*((\d{1,2}|[1-2]\d{2}|3([0-5]\d|60)))\s*,\s*((\d{1,2}|100)\s*%)\s*,\s*((\d{1,2}|100)\s*%)\))$/';
	\preg_match( $pattern, $value, $matches );
	// Return the 1st match found.
	if ( isset( $matches[0] ) ) {
		if ( is_string( $matches[0] ) ) {
			return $matches[0];
		}
		if ( is_array( $matches[0] ) && isset( $matches[0][0] ) ) {
			return $matches[0][0];
		}
	}
	// If no match was found, return an empty string.
	return '';
}
```

Autoloading
-----------

[](#autoloading)

You'll need to use an autoloader with this. Ideally, this would be [Composer](https://getcomposer.org). However, we have a [basic autoloader](https://github.com/WPTRT/autoload) available to include with themes if needed.

### Composer

[](#composer)

From the command line:

```
composer require wptrt/control-color-alpha
```

### WPTRT Autoloader

[](#wptrt-autoloader)

If using the WPTRT autoloader, use the following code:

```
include get_theme_file_path( 'path/to/autoload/src/Loader.php' );

$loader = new \WPTRT\Autoload\Loader();
$loader->add( 'WPTRT\\Customize\\Control', get_theme_file_path( 'path/to/control-color-alpha/src' ) );
$loader->register();
```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity27

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity60

Established project with proven stability

 Bus Factor1

Top contributor holds 74.4% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~118 days

Recently: every ~160 days

Total

7

Last Release

1707d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/471c510b2590bce99d5e41cc9b817f0c0d420f08d0930e70b18299f993ffa965?d=identicon)[aristath](/maintainers/aristath)

---

Top Contributors

[![aristath](https://avatars.githubusercontent.com/u/588688?v=4)](https://github.com/aristath "aristath (32 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (10 commits)")[![pattonwebz](https://avatars.githubusercontent.com/u/3902039?v=4)](https://github.com/pattonwebz "pattonwebz (1 commits)")

---

Tags

wordpress

### Embed Badge

![Health badge](/badges/wptrt-control-color-alpha/health.svg)

```
[![Health](https://phpackages.com/badges/wptrt-control-color-alpha/health.svg)](https://phpackages.com/packages/wptrt-control-color-alpha)
```

###  Alternatives

[tgmpa/tgm-plugin-activation

TGM Plugin Activation is a PHP library that allows you to easily require or recommend plugins for your WordPress themes (and plugins).

1.8k222.5k13](/packages/tgmpa-tgm-plugin-activation)[aristath/kirki

Extending the WordPress customizer

1.3k73.0k4](/packages/aristath-kirki)[afragen/git-updater

A plugin to automatically update GitHub, Bitbucket, GitLab, or Gitea hosted plugins, themes, and language packs.

3.3k1.6k](/packages/afragen-git-updater)[webdevstudios/cmb2-attached-posts

Custom field for CMB2 for creating post relationships.

13565.5k](/packages/webdevstudios-cmb2-attached-posts)[justintadlock/hybrid-carbon

God-like post featured image script.

202.5k](/packages/justintadlock-hybrid-carbon)[typisttech/wp-admin-notices

A simplified OOP implementation of the WordPress admin notices

141.2k](/packages/typisttech-wp-admin-notices)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
