Posted in WordPress by
Anthony Hortin
Updated: September 29 2017

In Part 1 of this series, I showed you how to start adding Customizer functionality to your theme (or plugin). As well as showing how to add Panels & Sections, I also walked through the process of creating the individual Settings and UI Controls, sanitizing your data, updating the live preview and retrieving your settings. In Part 2 we’re going to look at creating Customizer Custom Controls.

As we saw in Part 1, there are several different types of basic Core Controls that are ready to use straight-out-of-the-box. These include text, checkbox, textarea, radio, select and dropdown-pages controls. Later versions of WordPress also introduced Color, Media, Image and Cropped Image controls. If you want any other type of control, such as Sliders, On/Off Switches or Repeaters, for example, it’s up to you to develop them yourself.

Developing Custom Controls

If none of the basic core controls suit your needs, you can create and add your own custom controls. Custom Controls, Sections, and Panels can be created by subclassing the PHP objects associated with each Customizer object: WP_Customize_Control, WP_Customize_Section, and WP_Customize_Panel.

Subclassing the base control class allows you to override any functionality with your own custom functionality. The most common function to override is render_content(), which allows you to specify your own custom UI with HTML. Overriding the enqueue() function also allows you to enqueue your own css and JavaScript files.

1. Registering Customizer Custom Control Content

In Part 1 of this series we learned how to go about registering our Customizer content. To do this, we simply need to create a function that is used by the customize_register action hook.

Example

/**
 * Add our Customizer content
 */
function mytheme_customize_register( $wp_customize ) {
	// Add all your Customizer content (i.e. Panels, Sections, Settings & Controls) here...
);
add_action( 'customize_register', 'mytheme_customize_register' );

When creating Custom Controls, there’s also another way we can register our content. You can simply check for the existence of the WP_Customize_Control class.

/**
 * Add our Customizer content
 */
if ( class_exists( 'WP_Customize_Control' ) ) {
	// Add all your Customizer Custom Control classes here...
};

2. Creating our Custom Control Class

As mentioned above, to create our Custom Control we need to extend the WP_Customize_Control class. Once this is done, we then display our own html content for the control by overriding the render_content() function.

To show example of how to create a Custom Control, let’s create a simple notice control. All this control is going to do is allow you to display a heading label and some text.

/**
 * Simple Notice Custom Control
 */
class Skyrocket_Simple_Notice_Custom_Control extends WP_Customize_Control {
	/**
	 * The type of control being rendered
	 */
	public $type = 'simple_notice';
	/**
	 * Render the control in the customizer
	 */
	public function render_content() {
	?>
		


<div class="simple-notice-custom-control">
			<?php if( !empty( $this->label ) ) { ?>
				<span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span>
			<?php } ?>
			<?php if( !empty( $this->description ) ) { ?>
				<span class="customize-control-description"><?php echo wp_kses_post( $this->description ); ?></span>
			<?php } ?>
		</div>



	<?php
	}
}

As can be seen above, we simply override the render_content() function to display our new html. In this case, it’s displaying a label and a description. We’re also defining our control type using the $type variable.

Don’t forget, this code needs to be placed in one of the (two) places mentioned above in Registering Customizer Custom Control Content.

This Custom Control above is obviously very basic, for the sake of the example, and in fact, it doesn’t even let you save anything. All it’s doing is displaying some text. Most Custom Controls, like the core Controls, would typically allow you to save a value of some sort. This means that they’d typically have some type of UI component such as a slider, checkbox or something similar.

In the example control above, you can see that I’ve used $this->label when displaying the label for the control, and $this->description when displaying the description. These are the arguments that were specified when using add_control().

When creating your html for displaying the control in the render_content() function there are a number of other varaiables & methods that can, and should, be used when rendering your ui component. You can use $this->id to get the id for the control and $this->value() will get the default value. Probably the most important one though, is $this->link(), which outputs information for the customizer script. More specifically, it will create a “data-customizer-setting-link” attribute which links the control to the proper setting. You can see better examples of how these variables & methods are used in the exmaple code I’ll be linking to at the bottom of this post.

More than likely, your Custom Control is also going to need some custom css and/or Javascript. You can enqueue these scripts by overriding the enqueue() function.

Example

/**
 * Sample Custom Control
 */
class My_Awesome_Custom_Control extends WP_Customize_Control {
	/**
	 * The type of control being rendered
	 */
	public $type = 'sample_custom_control';
	/**
	 * Enqueue our scripts and styles
	 */
	public function enqueue() {
		// Enqueue our scripts here...
	}
	/**
	 * Render the control in the customizer
	 */
	public function render_content() {
		// Render our control HTML here...
	}
}

3. Using our New Custom Control

Now that our Custom Control has been created, it’s a simple matter of using our new control in the same way that we’d use one of the default built-in controls.

First up we need to add our setting, and after that, add our control. The only difference you’ll notice is that when we add our control we have to specify our new class that we created for our control.

Just like any other control, we also define our label and description that we want to display in the Customizer.

// Test of Sample Custom Control
$wp_customize->add_setting( 'sample_custom_control',
	array(
		'default' => '',
		'transport' => 'refresh',
		'sanitize_callback' => 'wp_filter_nohtml_kses'
	)
);
$wp_customize->add_control( new My_Awesome_Custom_Control( $wp_customize, 'sample_custom_control',
	array(
		'label' => __( 'Sample Custom Control' ),
		'description' 	=> esc_html__( 'This is the Custom Control description.' ),
		'section' => 'sample_custom_controls_section'
	)
) );

To use the setting for our new control in our theme, we use the get_theme_mod() function, just like we would for any other control. You can learn more about this in Retrieving Cutomizer Settings in Part 1.

4. Triggering Changes for your Control

When I started creating more complex controls, such as my Sortable Repeater, one of the issues I encountered is that when I changed the content in my control in the Customizer, the Save button at the top of the Customizer wouldn’t enable and therefore I couldn’t save my changes. This will most likely happen when you start using jQuery to dynamically alter the content of your control.

In my Sortable Repeater control, you can add a new input field by clicking the Add button. You can also drag and drop the fields to rearange their order. In the background, my jQuery script was simply getting the content of all the input fields, creating a comma separated string of all the content, and adding it to a (hidden) input field. It’s the content in this hidden input field that actually gets saved to the database.

The problem I was finding though was that when I did this, my Save button wasn’t getting enabled which meant that I couldn’t save my data. The solution, which took me ages to find, was that I needed to trigger a change event in my jQuery script. This would instruct the Customizer that the field has changed which in turn would enable the Save button.

Example

// Important! Make sure to trigger change event so Customizer knows it has to save the field
url.val('http://' + val).trigger('change');

5. Custom Controls

To help with your Customizer development, I’ve created a number of Custom Controls that you can use in your own theme or plugin. Over on my Github repo, you’ll find all the code for these Custom Controls, along with demo code for implementing these and all the core controls, in your theme.

The new Custom Controls that I’ve created are listed below. So as not to make this post incredibly long, I’m not going to list the PHP and jQuery for each control. Instead, I recommend you take a look at the Github repo if you’re interested in learning more about how these controls work.

5.1 Toggle Switch

The Toggle Switch Custom Control is basically just a fancy type of checkbox. It allows for two states, either off or on.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed. Default: Blank
section – Required. The Section where there control should appear

Example

$wp_customize->add_setting( 'sample_toggle_switch',
	array(
		'default' => 0,
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_switch_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Toggle_Switch_Custom_control( $wp_customize, 'sample_toggle_switch',
	array(
		'label' => esc_html__( 'Toggle switch' ),
		'section' => 'sample_custom_controls_section'
	)
) );

5.2 Slider

The Slider Custom Control allows you to drag a handle across a horizontal bar to increase or decrease a numeric value. The control also has a reset button, allowing you to reset the value back to the default value. The accompanying input field shows you the value of the slider whilst also giving you the ability to manually enter a value as well.

You can specify the minimum and maximum values for the slider as well as the step size, which is the size of each interval between the minimum and maximum values.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
section – Required. The Section where there control should appear
input_attrs – Required. List of custom input attributes for control output.
   min – Required. Minimum value for the slider
   max – Required. Maximum value for the slider
   step – Required. The size of each interval or step the slider takes between the min and max values

Example

$wp_customize->add_setting( 'sample_slider_control',
	array(
		'default' => 48,
		'transport' => 'postMessage',
		'sanitize_callback' => 'skyrocket_sanitize_integer'
	)
);

$wp_customize->add_control( new Skyrocket_Slider_Custom_Control( $wp_customize, 'sample_slider_control',
	array(
		'label' => esc_html__( 'Slider Control (px)' ),
		'section' => 'sample_custom_controls_section',
		'input_attrs' => array(
			'min' => 10, // Required. Minimum value for the slider
			'max' => 90, // Required. Maximum value for the slider
			'step' => 1, // Required. The size of each interval or step the slider takes between the minimum and maximum values
		),
	)
) );

5.3 Sortable Repeater

The Sortable Repeater Custom Control allows you to collect values from one or more input fields. On top of that, the fields can be reordered by simply dragging ‘n dropping each field. The control provides an icon handle for easy drag ‘n drop reordering, a button for deleting a row and a button for adding a new row.

This particular Control has been designed for collecting one or more URL’s and will validate the fields as such. It will also automatically add http:// to any url if it is missing. If you want to collect other type of data, such as plain text, simply duplicate this control and modify as necessary.

The setting for this control will be saved as a comma delimited string of URL’s. To use this setting in your theme, I recommend using the PHP explode() function to convert the comma delimited string to an array of strings.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Optional. The description to display under the label. Default: Blank.
section – Required. The Section where there control should appear
button_labels – Optional. Array containing a list of labels for the control
   add – Optional. Button label for add button. Default: Add

Example

$wp_customize->add_setting( 'sample_sortable_repeater_control',
	array(
		'default' => '',
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_url_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Sortable_Repeater_Custom_Control( $wp_customize, 'sample_sortable_repeater_control',
	array(
		'label' => __( 'Sortable Repeater' ),
		'description' => esc_html__( 'This is the control description.' ),
		'section' => 'sample_custom_controls_section',
		'button_labels' => array(
			'add' => __( 'Add Row' ), // Optional. Button label for Add button. Default: Add
		)
	)
) );

5.4 Image Radio Button

The Image Radio Button works the same as an ordinary radio button control, in that you can only choose one item out of a number of items. The difference is that it allows you to display images for each selection choice. This is useful where an image provides a better indicator for the user than simple text. A common use of this type of control is where a user might select the layout of their site.

When adding your control, you can specify the url for the image to display, the title text to display when hovering the cursor over the image and the value for each item.

Like an ordinary radio button, the setting that gets saved to the database is the key that you specify for each radio button choice.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Optional. The description to display under the label. Default: Blank.
section – Required. The Section where there control should appear
choices – Required. List of custom choices.
   key – Required. Data that will be stored for the setting
   image – Required. URL for the image to display
   name – Required. Title text to display

Example

$wp_customize->add_setting( 'sample_image_radio_button',
	array(
		'default' => 'sidebarright',
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_text_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Image_Radio_Button_Custom_Control( $wp_customize, 'sample_image_radio_button',
	array(
		'label' => __( 'Image Radio Button Control' ),
		'description' => esc_html__( 'Sample custom control description' ),
		'section' => 'sample_custom_controls_section',
		'choices' => array(
			'sidebarleft' => array(  // Required. Setting for this particular radio button choice
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/sidebar-left.png', // Required. URL for the image
				'name' => __( 'Left Sidebar' ) // Required. Title text to display
			),
			'sidebarnone' => array(
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/sidebar-none.png',
				'name' => __( 'No Sidebar' )
			),
			'sidebarright' => array(
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/sidebar-right.png',
				'name' => __( 'Right Sidebar' )
			)
		)
	)
) );

5.5 Text Radio Button

The Text Radio Button is another type of radio button, and again, works the same as an ordinary radio button control. The Text Radio Button simply displays the choices in a compact row of text.

When adding your control, you specify the text to display for each choice and the setting for each item.

Like an ordinary radio button, the setting that gets saved to the database is the value that you specify for each radio button choice.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Optional. The description to display under the label. Default: Blank.
section – Required. The Section where there control should appear
choices – Required. List of custom choices.
   key – Required. Data that will be stored for the setting
   value – Required. Data that is displayed for the radio button choice

Example

$wp_customize->add_setting( 'sample_text_radio_button',
	array(
		'default' => 'right',
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_radio_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Text_Radio_Button_Custom_Control( $wp_customize, 'sample_text_radio_button',
	array(
		'label' => __( 'Text Radio Button Control' ),
		'description' => esc_html__( 'Sample custom control description' ),
		'section' => 'sample_custom_controls_section',
		'choices' => array(
			'left' => __( 'Left' ), // Required. Setting for this particular radio button choice and the text to display
			'centered' => __( 'Centered' ), // Required. Setting for this particular radio button choice and the text to display
			'right' => __( 'Right' ) // Required. Setting for this particular radio button choice and the text to display
		)
	)
) );

5.6 Image Checkbox

The Image Checkbox works the same as an ordinary checkbox control, in that you can select one or more items out of a number of items. The difference is that it allows you to display images for each selection choice. This is useful where an image provides a better indicator for the user than simple text. A common use of this type of control is where a user might select the weight of a font (e.g. Bold, Italic etc.).

When adding your control, you can specify the url for the image to display, the title text to display when hovering the cursor over the image and the value for each item.

The setting that gets saved to the database is a comma-separated string of values for each of the items that are selected.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Optional. The description to display under the label. Default: Blank.
section – Required. The Section where there control should appear
choices – Required. List of custom choices.
   key – Required. Data that will be stored for the setting
   image – Required. URL for the image to display
   name – Required. Title text to display

Example

$wp_customize->add_setting( 'sample_image_checkbox',
	array(
		'default' => 'stylebold,styleallcaps',
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_text_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Image_checkbox_Custom_Control( $wp_customize, 'sample_image_checkbox',
	array(
		'label' => __( 'Image Checkbox Control' ),
		'description' => esc_html__( 'Sample custom control description' ),
		'section' => 'sample_custom_controls_section',
		'choices' => array(
			'stylebold' => array( // Required. Setting for this particular radio button choice
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/Bold.png', // Required. URL for the image
				'name' => __( 'Bold' ) // Required. Title text to display
			),
			'styleitalic' => array(
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/Italic.png',
				'name' => __( 'Italic' )
			),
			'styleallcaps' => array(
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/AllCaps.png',
				'name' => __( 'All Caps' )
			),
			'styleunderline' => array(
				'image' => trailingslashit( get_template_directory_uri() ) . 'images/Underline.png',
				'name' => __( 'Underline' )
			)
		)
	)
) );

5.7 Single Accordion

The Single Accordion Control allows you to display a large block of text such as instructional information, whilst keeping it hidden or minimised until clicked. When the control is clicked, the content will become visible and when clicked again, the content will hide.

There’s no settings saved for this control, it’s purely for showing/hiding a block of content.

You can pass it an array of key/values pair that will get displayed as a list, or just plain text content (incl. basic html tags a, br, em, strong, i).

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Required. The text to hide under the accordion, passed as an array or string
section – Required. The Section where there control should appear

Example

// Example 1
$sampleIconsList = array(
	'Behance' => __( '<i class="fa fa-behance"></i>', 'ephemeris' ),
	'Bitbucket' => __( '<i class="fa fa-bitbucket"></i>', 'ephemeris' ),
	'CodePen' => __( '<i class="fa fa-codepen"></i>', 'ephemeris' ),
	'DeviantArt' => __( '<i class="fa fa-deviantart"></i>', 'ephemeris' ),
	'Dribbble' => __( '<i class="fa fa-dribbble"></i>', 'ephemeris' ),
	'Etsy' => __( '<i class="fa fa-etsy"></i>', 'ephemeris' ),
	'Facebook' => __( '<i class="fa fa-facebook"></i>', 'ephemeris' ),
	'Flickr' => __( '<i class="fa fa-flickr"></i>', 'ephemeris' ),
	'Foursquare' => __( '<i class="fa fa-foursquare"></i>', 'ephemeris' ),
	'GitHub' => __( '<i class="fa fa-github"></i>', 'ephemeris' ),
);

$wp_customize->add_setting( 'sample_single_accordion',
	array(
		'default' => '',
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_text_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Single_Accordion_Custom_Control( $wp_customize, 'sample_single_accordion',
	array(
		'label' => __( 'Single Accordion Control' ),
		'description' => $sampleIconsList, // Required. Passing an array of key/values pairs which are displayed in a list
		'section' => 'sample_custom_controls_section'
	)
) );

// Example 2
$wp_customize->add_setting( 'another_sample_single_accordion',
	array(
		'default' => '',
		'transport' => 'refresh',
		'sanitize_callback' => 'skyrocket_text_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Single_Accordion_Custom_Control( $wp_customize, 'another_sample_single_accordion',
	array(
		'label' => __( 'Another Single Accordion Control' ),
		'description' => __( 'This is some simple text with an <a href="http://google.com">html link</a> included.' ),  // Required. Passing some text with some basic html content
		'section' => 'sample_custom_controls_section'
	)
) );

5.8 Simple Notice

The Simple Notice Control allows you to display a block of text such as instructional information. There’s no settings saved for this control, it’s purely for displaying a block of content.

The text content can include basic html tags such as a, br, em, strong, i, span and code.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Required. The text to display
section – Required. The Section where there control should appear

Example

$wp_customize->add_setting( 'sample_simple_notice',
	array(
		'default' => '',
		'transport' => 'postMessage',
		'sanitize_callback' => 'skyrocket_text_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Simple_Notice_Custom_control( $wp_customize, 'sample_simple_notice',
	array(
		'label' => __( 'Simple Notice Control' ),
		'description' => __( 'This Custom Control allows you to display a simple title and description to your users. You can even include <a href="http://google.com" target="_blank">basic html</a>.' ),
		'section' => 'sample_custom_controls_section'
	)
) );

5.9 TinyMCE Editor

The TinyMCE editor works the same as the standard TinyMCE Editor that you use when creating a Page or Post. The only difference you’ll notice is that it has a minimalist toolbar. This is mainly because you’re not likely to need the same full-featured toolbar as you would when creating a Page or Post. It’s also due, in part, to the limited screen space available in the Customizer sidebar. Like the standard Page/Post TinyMCE editor, you can add text & links, along with various styles such as bold, italics and a number of other styles.

When adding your control, you can also specify what toolbar icons you would like to display. You can have one toolbar row or two toolbar rows. If you don’t specify any toolbars, the default is to display one toolbar with bold, italic, bullet list, number list, align left, align center, align right and link buttons.

The full list of available toolbar buttons is available on the official TinyMCE website. Their Examples & Demo pages also has a number of examples showing how each of the toolbar buttons would display. It’s worth noting that some toolbar buttons require additional TinyMCE plugins, not all of which are available by default in the WordPress version of TinyMCE.

When sanitzing your setting, you can simply use the core wp_kses_post() function, which will sanitize the content for allowed HTML tags for post content.

The setting that gets saved to the database will be a string with the allowed HTML tags and attributes intact.

Please note: The TinyMCE Editor Custom Control will only work in WordPress 4.8 and above as the JavaScript functionality required for its use was only added in WP 4.8

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Required. The text to display
section – Required. The Section where there control should appear
input_attrs – Optional. List of custom choices.
   toolbar1 – Optional. String containing a list of toolbar buttons to display on the first toolbar row. Default: ‘bold italic bullist numlist alignleft aligncenter alignright link’
   toolbar2 – Optional. String containing a list of toolbar buttons to display on the second toolbar row. Default: blank

Example

$wp_customize->add_setting( 'sample_tinymce_editor',
	array(
		'default' => '',
		'transport' => 'postMessage',
		'sanitize_callback' => 'wp_kses_post'
	)
);
$wp_customize->add_control( new Skyrocket_TinyMCE_Custom_control( $wp_customize, 'sample_tinymce_editor',
	array(
		'label' => __( 'TinyMCE Control' ),
		'description' => __( 'This is a TinyMCE Editor Custom Control' ),
		'section' => 'sample_custom_controls_section',
		'input_attrs' => array(
			'toolbar1' => 'bold italic bullist numlist alignleft aligncenter alignright link',
		)
	)
) );

5.10 Google Font Select

One of the issues I’ve found with a lot of Google Font controls in numerous themes and plugins is that they don’t allow for Italic and Bold weights. They’ll change the regular text to the chosen font, but any text that you make bold or italic, reverts back to the original font. One of the reasons for this is because they don’t specify the necessary italic and bold weights when retrieving the fonts from Google.

The Google Font Control will allow you to select a Google font and also specify the weight for the regular, italic and bold weights. The list of font choices are stored in a json file generated by retrieving the 30 most popular Google fonts. So as to avoid having to include your own Google Fonts API Key in your theme, you should generate this list of fonts before you add your theme options. You can get the complete list of Google Fonts, sorted by popularity, by calling https://www.googleapis.com/webfonts/v1/webfonts?sort=popularity&key=YOUR-API-KEY (Don’t forget to include your own Google Fonts API Key in the appropriate place).

The setting is saved to the database as a json string. The easiest way to use this data in your theme is by using the json_decode() PHP function to convert the json string into an array. From there, it’s easy enough to get the Font name, regular font weight, italic weight, bold weight, and the font category which is useful for specifying a fallback font.

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Optional. The text to display
section – Required. The Section where there control should appear

Example

$wp_customize->add_setting( 'sample_google_font_select',
	array(
		'default' => json_encode(
			array(
				'font' => 'Open Sans',
				'regularweight' => 'regular',
				'italicweight' => 'italic',
				'boldweight' => '700',
				'category' => 'sans-serif'
			)
		),
		'sanitize_callback' => 'skyrocket_google_font_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Google_Font_Select_Custom_Control( $wp_customize, 'sample_google_font_select',
	array(
		'label' => __( 'Google Font Control' ),
		'description' => esc_html__( 'Sample custom control description' ),
		'section' => 'sample_custom_controls_section',
	)
) );

5.10 Alpha Color Picker

All props for this control go to Braad Martin. I’ve included it here (and also in my sample code) because it’s so useful and I think it’s a better option than the standard Color Control built into core. You can check out the original post Braad wrote about this control or check it out in his Github repo.

The Alpha Color Control is very similar to the Color Control built into core. The benefit of this control over the default control, is that it allows you to specify the opacity of the selected colour, which allows you to specify RGBa colours rather than just a solid hex colour.

The setting that gets saved to the database will be an RGBa color value (e.g. rgba(0,158,39,0.8) ) or a plain solid hex color (e.g. #009e27).

Usage
add_control( $id, $args );

Parameters
$id – (string) (required) The id of the Setting associated with this Control. Default: None

$args – (array) (required) An associative array containing arguments for the setting. Default: None

Arguments for $args
label – Optional. The label that will be displayed Default: Blank
description – Optional. The text to display
section – Required. The Section where there control should appear
show_opacity – Optional. Show or hide the opacity value on the opacity slider handle. Default: true
palette – Optional. Allows you to specify the colours used in the colour palette. Can be set to false to hide the palette. Default: WP color control palette

Example

$wp_customize->add_setting( 'sample_alpha_color',
	array(
		'default' => 'rgba(209,0,55,0.7)',
		'transport' => 'postMessage',
		'sanitize_callback' => 'skyrocket_hex_rgba_sanitization'
	)
);

$wp_customize->add_control( new Skyrocket_Customize_Alpha_Color_Control( $wp_customize, 'sample_alpha_color_picker',
	array(
		'label' => __( 'Alpha Color Picker Control' ),
		'description' => esc_html__( 'Sample custom control description' ),
		'section' => 'sample_custom_controls_section',
		'show_opacity' => true, // Optional. Show or hide the opacity value on the opacity slider handle. Default: true
		'palette' => array( // Optional. Select the colours for the colour palette . Default: WP color control palette
			'#000',
			'#fff',
			'#df312c',
			'#df9a23',
			'#eef000',
			'#7ed934',
			'#1571c1',
			'#8309e7'
		)
	)
) );

6. Summary

Hopefully this second part of my Customizer Developers Guide gives you a fairly good understanding of how to create your own Custom Controls. Along with Part 1 of this guide, you should be well on your way to adding Customizer functionality to your theme or plugin.

As mentioned above, I’ve added some sample code to Github which will show you how to use the built-in core Controls, along with all these new Custom Controls. There’s also some example code for implementing Live Preview refreshes. You can check out all that code in my Customizer Custom Controls repo on Github.

See also: The WordPress Customizer – A Developers Guide (Part 1)

4 responses on “The WordPress Customizer – A Developers Guide (Part 2)

  1. Braad Martin

    Awesome series on the Customizer! This is exactly the kind of thorough content that really helps the WP dev community. Glad you like my Alpha Color Picker control also 🙂

    1. Anthony Hortin Post author

      Thanks Braad. I appreciate the kind words. And thanks also for creating that Alpha Color Picker. It works really well and as I said above, I think it’s a much more useful option than the standard color control.

  2. Kevin Damstra

    This is it! Thank you so much for sharing your knowledge about these custom controls. I couldn’t get my TinyMCE working but with your tutorial, piece of cake!

    There’s not a lot of documentation on this subject out there, Keep up the good work!