Está en la página 1de 42

Beginners guide to WordPress Customizer

Learn how customizer your themes with WordPress


Customizer
Igor Beni
This book is for sale at http://leanpub.com/wpcustomizer
This version was published on 2015-01-14

This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
2014 - 2015 Igor Beni

Contents
Prologue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Who is this book for? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

WordPress Customizer 101 . . . . . . . . .


Where can I find WordPress Customizer?
How to use WordPress Customizer? . . .
WordPress Customizer Structure . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

3
3
4
6

Developing your Theme Customizer .


How to define a Customizer Option .
Defining a Panel . . . . . . . . . . . .
Registering our Customizer . . . . . .
Setting our Child theme . . . . . . . .
Create your first Customizer Option .
Creating our first section with options

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

9
9
11
11
12
13
17

Developing your custom control .


How to develop a custom control
Custom Category Control . . . .
Custom Layout select . . . . . . .
Custom Dynamic Layout Control

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

26
26
26
29
31

Using other resources to develop . .


Paul Underwoods Custom Controls
Kirki Plugin . . . . . . . . . . . . .
Titan Framework . . . . . . . . . .
Plugin Customizer . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

34
34
35
36
38

Prologue
WordPress is a very popular CMS in the world of websites. In its previous version 3.4., WordPress
introduced a new way of designing and configuring a theme without the need of developing and
using Settings API. This new way provided us with a real example so we can see how the changes
will affect are website and if we dont like it or it breaks up our website we can just easily click on
Cancel.
This new way of customizing our themes is called WordPress Customizer.

Who is this book for?


Beginners guide to WordPress Customizer is written for all beginners and skilled developers who
want to find out how to use WordPress Customizer, develop options for it and even create custom
input controls.
You will learn the basics of WordPress Customizer and how it operates. You will also learn how to
enable a Live preview of WordPress Customizer and how to implement it into your themes (existing
or under development).

WordPress Customizer 101


In this chapter we will look into it how the Customizer can be used and where can we find it.

Where can I find WordPress Customizer?


WordPress Customizer is situated in the menu Appearance > Customize. Unlike Widgets, Sidebar
and Menus WordPress Customizer is available on every theme without the need to register it.

Customizer Menu

By selecting Customize you will be redirected on the Customizer page where you can see your
theme appear and here you can change the provided settings and look how the changes appear on
you theme.

Customizer Page

We are using the theme Twenty Fourteen which is provided by WordPress itself and therefore I am
sure that you can get this theme working and showing on your WordPress site and follow these
chapters and the whole book along with ease.

WordPress Customizer 101

How to use WordPress Customizer?


WordPress Customizer is fairly easy to use and it provides options that are really intuitive/familiar
so the users wont and shouldnt have any difficulties using the WordPress Customizer.
When we arive to the WordPress Customizer page we are presented with a panel on the left side and
our site on the right. The sections and options depend on the theme we are using and its Customizer
defined settings that are set through the code.

WordPress Customizer 101

Customizer Panel

By clicking on a section, it will collapse and we will get all the options (Customizer Controls) that
are connected to that section.

WordPress Customizer 101

Customizer Section Collapsed

There are two ways how a change is presented in the right side (our website):
refresh
live
Depending on the Customizer definition for the theme we are using, we can have one of those ways
or both of them because it all depends how an option is defined in the code.
If it is set to refresh the website, after we are done with the change our website on the right side
will refresh and show the changed data, but if it is set on live, we will see the change as we change
the data without the need to refresh. The later requires a bit of javascript to be able to operate and
change the data.
When we are done with all the changes and we are happy how our website looks and feels, we can
publish those changes and our website will be represented with the new data.

WordPress Customizer Structure


Now, when we know how to use WordPress Customizer we can look at the structure of it because
we can picture all the parts in our head. WordPress Customizer consists of:
1.
2.
3.
4.

Panels
Sections
Settings
Controls

WordPress Customizer 101

Customizer Panels
Panels were introduced in WordPress 4.0 and they are the containers of sections. We can use
Customizer Panels to better organize the WordPress Customizer for our theme and therefore make
it even easier for a regular user to distinguish between regular Customizer settings and the current
themes Customizer settings.

Customizer Panels

To distinguish panels from regular sections in Customizer, they are presented with a different arrow
on the right side of the panel. Arrow that is representing a new panel is oriented horizontally, thus
pointing to the right while a section arrow is oriented vertical and pointing down.

Customizer Sections
Customizer Sections are containers of controls which are used to save options. Each section can be
collapsed and uncollapsed to show the available controls under the chosen section.

WordPress Customizer 101

Collapsed Section

Customizer Settings
When talking about settings in WordPress Customizer we are actually referring to the values that
are inserted and saved in the database. Those options can be easily retrieved by using WordPress
API calls such as get_theme_mod or get_option.

Customizer Controls
Customizer Controls are input types for registered Customizer Settings. They are defining the way a
user can insert or update an option (value in database). WordPress comes with six different controls:

Plain Text input


Color Wheel
Uploader of media
Uploader and Selector of an image
Selector for background image
Selector for header image

In addition, Customizer Controls can be developed so each theme can have their custom controls
that are used to control the design, content or even functionality of the theme.
http://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_control

Developing your Theme Customizer


In this section we will make additional WordPress Customizer sections, controls and option upon
a child theme. We will use a child theme so we dont interfere with the functionality of the parent
theme. In this way we can add other WordPress Customizer settings just by extending the parent
theme with our child theme.

How to define a Customizer Option


The Customizer Option is defined by several parts. The definition contains the value (setting), section
in which it is presented and the control which is used to output the input for this option.
Lets do it in that order.
Defining the setting
1
2
3
4
5
6
7
8
9
10
11

$wp_customize->add_setting( 'option_id' , array(


'default' => 'Starting Value',
'transport' => 'refresh or postMessage',
'type' => 'option or theme_mod',
'capability' => 'ex. manage_options | show this option only to the users
with this capabaility'
'theme_supports' => 'show this option if the theme supports a theme feature',
'sanitize_callback' => 'function to validate the input',
'sanitize_js_callback' => 'function to check the value given by database to
customizer'
) );

All we need to define a setting is its ID and the default value which can be set to which is none.
Defininig the section
Section does not have to be defined since there are several sections already defined within WordPress
Customizer. If we want to develop a set of options which are referring only to our theme or something
similar, we can then define another section to group them separately from other options.

Developing your Theme Customizer

1
2
3
4
5
6

10

$wp_customize->add_section( 'section_id' , array(


'title' => __( 'Section Title', 'wp_localize' ),
'priority' => 30,
'description' => __('Section Description', 'wp_localize'),
'panel_id' => 'panel_id'
) );

The priority parameter defines the position of the section among other sections. The parameter
panel_id is avaiable from WordPress 4.0 and above.
If we want to define options which are connected in some way with the existing sections, we do not
need to define a new section. The existing sections are:

title_tagline - Site Title and Description


colors - Colors
header_image - Header Image
background_image - Background Image
nav - Navigation
static_front_page - Static Front Page

Defining the control


The Control is the middle man between sections and settings. They are defining in which section
does a setting apear and in which way (input type).
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

$wp_customize->add_control(
new WP_Customize_Control(
$wp_customize,
'control_id',
array(
'label' => __( 'Control Text', 'wp_localize' ),
'section' => 'section_id',
'settings' => 'setting_id',
'active_callback' => 'is_front_page', //ex. show this only on front page
'type' => 'text, textarea, checkbox, radio, select or dropdown-pages',
//If radio or select is selected then we need also choices
'choices' => array(
'dark' => __( 'Dark' ),
'light' => __( 'Light' )
),
),

Developing your Theme Customizer

18
19
20
21
22
23
24
25
26

11

'input_attrs' => array(


'min'
=> 0,
'max'
=> 10,
'step' => 2,
'class' => 'test-class test',
'style' => 'color: #0a0',
),
)
);

The parameters active_callback and input_attrs are avaiable from WordPress 4.0 and above. All the
attributes defined in the parameter input_attrs are then displayed in the element input as attributes.
1
2

<input type="range" min="0" max="10" step="2" class="test-class test"


style="color: #0a0;" value="">

Type textarea is available from WordPress 4.0 and above. For any type of input that uses an input
element, you can simply specify the type attribute using the type parameter such as range.

Defining a Panel
Panels are optional and they are not required to be made but they can be if needed. Customizer
Panels were introduced in WordPress 4.0 so before that you cannot use them.
1
2
3
4
5
6
7

$wp_customize->add_panel( 'panel_id', array(


'priority'
=> 10,
'capability'
=> 'edit_theme_options',
'theme_supports' => '',
'title'
=> '',
'description'
=> '',
) );

Registering our Customizer


Before we can use the above defined Customizer Options with or without Panels, we must still
register all of the above settings. This is easily done by calling the action customize_register. If we
now imagine that the above defined settings, sections, control and panels are placed inside a function
my_theme_customizer we would be registering it like this:

Developing your Theme Customizer

12

add_action('customize_register', 'my_theme_customizer');

Setting our Child theme


Since we are using from the start Twenty Fourteen, we will make a child theme of that theme. Go
to the folder of themes which is generally your_wordpress_installation/wp-content/themes/. Create
a new folder called twentyfourteen-child and make a file style.css with this content:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

/*
Theme Name:
Theme URI:
Description:
Author:
Author URI:
Template:
Version:
Tags:
Text Domain:
*/

Twenty Fourteen Child


http://example.com/twenty-fourteen-child/
Twenty Fourteen Child Theme
John Doe
http://example.com
twentyfourteen
1.0.0
light, dark, two-columns, right-sidebar, responsive-layout,
accessibility-ready
twenty-fourteen-child

@import url("../twentyfourteen/style.css");
/* =Theme customization starts here
-------------------------------------------------------------- */

With the line @import we are using the default style from the parent theme and by that we dont
need to develop a custom theme css.
After that you have saved your style.css create another file functions.php. This file will be used
to develop our WordPress Customizer for our child theme. The child theme calls and uses the
functions.php from the parent theme so we will not lose any WordPress Customizer control, option,
section or panel defined by the parent theme. The functions.php in the child theme will be used to
extend the current WordPress Customizer settings by adding additional controls or even sections
and panels.
In the functions.php add just one line:
1

<?php

Developing your Theme Customizer

13

Create your first Customizer Option


For our first Customizer Option we will add a new background color setting that will be added to
the color section in WordPress Customizer.
If we are to follow the order described in previous sections we will define the inital setting first. Lets
define our function that will be hooked and registered to WordPress customizer with its setting,
section and control.
1
2
3
4
5

function wpcustomizer_firstOption($wp_customize){
//Here goes our code
}
add_action('customize_register', 'wpcustomizer_firstOption');

We will now define a new setting that will be called wpcustomizer[Color] and it will be used to
set a new background color of the entire web site. That means that the color will be added to the
element body through CSS. We are defining this options as an array because then we can define
several options by one name such as wpcustomizer and each particular option will be saved under
a name. In that way it will be easier to remember, call and even maintain the option or options.
Add this code in the newly defined function wpcustomizer_firstOption:
1
2
3
4
5
6
7
8

$wp_customize->add_setting( 'wpcustomizer[Color]' , array(


'default' => '#ffffff',
'transport' => 'postMessage',
'type' => 'option',
'capability' => 'manage_options'
)
);

Now that we have defined our first setting, we need to create a Control for it which will be a
colorwheel. We do not need to define a new section or panel because we are defining an option to
change the a color and this part should go in the section Color.
After the defined setting define a new control and connect the setting with the section by this control.

Developing your Theme Customizer

1
2
3
4
5
6
7
8
9
10
11

14

$wp_customize->add_control(
new WP_Customize_Color_Control(
$wp_customize,
'wpcustomizer[Color]',
array(
'label'
=> __( 'Background Color by WpCustomizerOption',
'your_wpcustomizer' ),
'section'
=> 'colors',
'settings'
=> 'wpcustomizer[Color]',
) )
);

What have we done until now? We have defined a new setting which its change will be viewed
and seen instantly without the need to refresh the window (transport postMessage). We have
also defined it as an option since I have encountered a problem with saving and retrieving the value
from theme_mod.
After our setting defined we have defined a Customizer Control that represent a colorwheel where
we can choose a color from the wheel and connects the setting with a section.
Now go to your wordpress administration and if you did not activate the child theme, activate it
now. After that go to the customizer by following this path Appearance > Customize. You should
see the new option under the section Colors.

New Color Option with a different color setting

Choose a color and try to save it. Refresh the customizer and you will see that the new color is saved.
Now we have to create a tiny javascript function that will set the color to the body element.

Developing your Theme Customizer

15

Live Customizer Change


We need to create a new javascript file so lets make one in the same directory as our files
(functions.php and style.css) are. Name it customizer.js and save it. Before we do any coding, lets
enqueue it so it will be called on the preview of Customizer. Write this at the end of the functions.php
file:
1
2
3
4
5
6
7
8
9
10
11

function wpcustomizer_live_preview()
{
wp_enqueue_script(
'wpcustomizer-myjs',
//Give the script an ID
get_stylesheet_directory_uri().'/customizer.js',//Point to file
array( 'jquery','customize-preview' ),
//Define dependencies
'',
//Define a version (optional)
true
//Put script in footer?
);
}
add_action( 'customize_preview_init', 'wpcustomizer_live_preview' );

Here we have enqueued our javascript file so that our functions in javascript are called and processed
in the preview of our theme (in Customizer). Now we can write our code so that our elements will
change as we change them by, for example, changing the color. Go to the customizer.js file and write
next:
1
2
3
4
5
6
7
8
9

( function( $ ) {
wp.customize( 'wpcustomizer[Color]', function( value ) {
value.bind( function( newval ) {
$('body').css('backgroundColor', newval );
} );
} );
} )( jQuery );

Here we are defining a new function for the registered setting. This function will parse a value on
which we will bind the new value and we set the new value to the body element. Now you can refresh
your customizer page so the changes will take effect and by changes I mean that the javascript file
will be loaded in Customizer Preview.

16

Developing your Theme Customizer

Changing the color for the background

While you change your setting you will see that the body of the theme will also have the same color
you are setting.

Body changes the color

Displaying the new color on the real site


As for now, we can only see the changes in the Customizer Preview section. To be able to see also
on the front web and present it to our users who are viewing our site, we need to define another
function which will get the newly saved option and set the value to the body element.
Open the functions.php and at the bottom write this:

Developing your Theme Customizer

1
2
3
4
5
6
7
8
9
10
11
12

17

function wpcustomizer_css()
{
$ourCustomizerOptions = get_option('wpcustomizer');
?>
<style type="text/css">
body {
background-color:<?php echo $ourCustomizerOptions["Color"]; ?>;
}
</style>
<?php
}
add_action( 'wp_head', 'wpcustomizer_css');

We have defined a function which at the beginning gets our option wpcustomizer and since we have
defined our first option to be just a part of this option array we will access our value by using the call
ourCustomizerOptions[Color]. We are then writing a standard style element to write some CSS in
it. We have defined here a CSS rule to set the background color of the body to the newly saved
value. By hooking this function to the wp_head we ensure that this piece of code will be executed
and shown at the end of the head element, after all CSS files are already loaded.

Creating our first section with options


We will create now a section with an option. This will be an example of a section with an option
to upload an image. This image will be displayed as a background image since we are using the
twentyfourteen theme look and feel we have only the right side available to do such thing. The other
option will be a radio button that will give us a choice to have the background image positioned on
top, center or bottom of the right side or we can even set a repeating property for the image.
Open up the functions.php and add a new function with a defined section:
1
2
3
4
5
6
7
8
9
10
11
12

function wpcustomizer_secondOption($wp_customize){
$wp_customize->add_section( 'sectionExampleID' , array(
'title' => __( 'WP Customizer Section', 'your_wpcustomizer' ),
'priority' => 30,
'description' => __('This is an example of a section',
'your_wpcustomizer'),
) );

Developing your Theme Customizer

13
14

18

add_action('customize_register', 'wpcustomizer_secondOption');

Here we have defined our section with an id sectionExampleID and we named it WP Customizer
Section. Now, after the section definition add a setting (inside the function wpcustomizer_secondOption.
1
2
3
4
5
6
7
8

$wp_customize->add_setting( 'wpcustomizer[Image]' , array(


'default' => '',
'transport' => 'postMessage',
'type' => 'option',
'capability' => 'manage_options'
)
);

With this code we have defined a new setting which is saved also in the wpcustomizer option that
we started using in the last chapter. Now we are saving another setting with the key Image. The last
thing we have to set is a control to upload the image.
1
2
3
4
5
6
7
8
9
10
11

$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'wpcustomizer[Image]',
array(
'label'
=> __( 'Background Image by WpCustomizerOption',
'your_wpcustomizer' ),
'section'
=> 'sectionExampleID',
'settings'
=> 'wpcustomizer[Image]',
) )
);

This is a new control WP_Customize_Image_Control. With this control we will have a form to upload
an image and use that image for our background image. We have assigned the new section we created
with the new setting. Now if you open up the WordPress Customizer in your localhost or a site you
are developing you will see this new section and the form to upload the image.

19

Developing your Theme Customizer

Customizer Image Control

Showing the uploaded image


Try to upload an image. It is very intuitive so it should not be a problem to upload a new image with
this control. To show this image we will use a function which we have defined when we created our
first option. Go to the file customizer.js so we can set a live preview of the image before we go and
set the CSS that is used for the live site. After the defined javascript for the option Color, set this:
1
2
3
4
5

wp.customize( 'wpcustomizer[Image]', function( value ) {


value.bind( function( newval ) {
$('body').css('backgroundImage', 'url("'+newval+'")' );
} );
} );

Save the file customizer.js and reload your Customizer window. Now try to upload an image. You
will see how the image gets set in the background and repeated.

20

Developing your Theme Customizer

Customizer Image Control

Developing your Theme Customizer

21

Lets implement also the actual saved value on the true version of our site. This will be done by
adding the next code block into the function wpcustomizer_css inside the style element.
1

body {background-image:url('<?php echo $ourCustomizerOptions["Image"]; ?>');}

Now we have two same CSS selectors and this values should be placed under one selector if they
are the same, so our style element should look like this:
1
2
3

body { background-color:<?php echo $ourCustomizerOptions["Color"]; ?>;


background-image:url('<?php echo $ourCustomizerOptions["Image"]; ?>');
}

So what if we uploaded a really small image? What if we want to make a possibility for the user of
our theme to set a small image with a position of top right? This can all be done with the Customizer
Controls and we will do it now.

Option for background repeat


CSS can have a few repeating values:

no-repeat
repeat
repeat-x
repeat-y
inital
inherit

We will now implement a new option for four repeating cases: no-repeat, repeat-x, repeat-y and
repeat. Lets define our setting. Inside the function wpcustomizer_secondOption insert this:
1
2
3
4
5
6
7
8

$wp_customize->add_setting( 'wpcustomizer[ImageRepeat]' , array(


'default' => 'no-repeat',
'transport' => 'postMessage',
'type' => 'option',
'capability' => 'manage_options'
)
);

With this we have defined our new setting with a default value of no-repeat. Now we only need to
make a Customizer Control that will generate a radio input with 4 different values. After the upper
code block insert this:

Developing your Theme Customizer

1
2
3
4
5
6
7
8
9
10
11
12
13
14

22

$wp_customize->add_control(
'wpcustomizer[ImageRepeat]',
array(
'type' => 'radio',
'label' => 'Image placement',
'section' => 'sectionExampleID',
'choices' => array(
'no-repeat' => 'No Repeat',
'repeat' => 'Repeat',
'repeat-x' => 'Repeat X',
'repeat-y' => 'Repeat Y',
),
)
);

We have asigned a Customizer Control to our newly added section and to our option. This control
has a different key value in its array which is a requirement when we are setting the control to type
radio. This key is choices and it contains several options which are in this case CSS values.
Showing the repeat setting in CSS
Last time we had first defined the live preview before we have actually implemented the CSS setting
to show the actual image on the front side of our website. Now we will do the opposite and we will
first set the CSS setting and after that we will add the live preview option with javascript.
Add the following snippet inside the body element:
1

background-repeat: <?php echo $ourCustomizerOptions["ImageRepeat"]; ?>;

Now if you set to the default value of no-repeat and save it, after you refresh you will not see
anything because the image starts from left-to-right and therefore you cannot see it since it is placed
behind the whole content page.
Try another setting such as repeat-x. The image should be shown only in the first row.
Add Live Preview
Adding live preview is now really easy because we just need to follow the same pattern we used
with the last options and just change the appropriate value, so lets open the file customizer.js and
add the following under the last option:

Developing your Theme Customizer

1
2
3
4
5

23

wp.customize( 'wpcustomizer[ImageRepeat]', function( value ) {


value.bind( function( newval ) {
$('body').css('backgroundRepeat', newval );
} );
} );

Now the image will be placed/shown differently everytime you choose another value for the
repeating option.
So now we can change the repeating of our image, but what if we want to have a non repeating
image that is displayed on the top right or maybe even top middle?

Adding the option for image position


The background position property in CSS can have various options. The value can be set in numbers,
percentage and even words such as top right or bottom left. This can be done in various steps where
we could define one option which will give us information on which value will we use and another
where we store the value or we could define on option as a text input where we could insert our
desired position and then show it in CSS.
By doing this, we should have also a callback function which will check the input value and configure
it if possible. Lets do that. In the functions.php add another setting:
1
2
3
4
5
6
7
8

$wp_customize->add_setting( 'wpcustomizer[ImagePosition]' , array(


'default' => 'top right',
'transport' => 'postMessage',
'type' => 'option',
'capability' => 'manage_options',
'sanitize_callback' => 'check_position'
)
);

Here we have set already a default value that will be used if nothing is changed. Now we need to
insert also a Customizer Control. We have also defined a callback function that will be used to check
the value that is sent to database. Now lets add the control:

Developing your Theme Customizer

1
2
3
4
5
6
7
8
9
10
11
12

24

$wp_customize->add_control(
'wpcustomizer[ImagePosition]',
array(
'type' => 'text',
'label' => 'Position value (y x). Can be set as
percentage (40%), number in pixels (23px) or even text
(center,top,bottom,left,right)',
'section' => 'sectionExampleID',

)
);

With this we can now set the various positions for the image. Before we do that we need to define
our callback function so outside the function we need to define another function. Add this to the
bottom of functions.php:
1
2
3
4
5
6
7
8
9
10
11

function check_position($input){
$string = trim($input);
if (strpos($string, ' ') !== false) {
//We have two words
$string = strip_tags($string);
return $string;
}
return "top right";
}

We trim the input we get before WordPress saves it in the database. We then check if there is a space
in the string which means that there are actually two or more words. If that is not right the function
returns our default value top right. If the input contains two words they will be stripped of tags so
there is not HTML, PHP or similar tags in it and after that we return it to the database.
Before we go and actually display it in CSS we need to set a live preview for this option. Open our
file customizer.js and before
1

} )( jQuery );

insert this:

Developing your Theme Customizer

1
2
3
4
5

25

wp.customize( 'wpcustomizer[ImagePosition]', function( value ) {


value.bind( function( newval ) {
$('body').css('backgroundPosition', newval );
} );
} );

Here we are now getting the new value and setting it as a CSS property (background-position) of
the body element.
After that we just need to set also a CSS property which will be rendered when the page is requested.
Lets go back to the file functions.php and in the function wpcustomizer_css, inside the body
element insert this CSS rule:
1

background-position: <?php echo $ourCustomizerOptions["ImagePosition"]; ?>;

Now our body will also set the position of the background image, if there is any.

Developing your custom control


In this part of our development chapter we will learn how to develop our own customizer controls
which then we can use in our themes or plugins.

How to develop a custom control


To develop our custom controls we need to know a little bit of OOP PHP but at this point it
does not actually require any knowledge of OOP since we will just follow a pattern. To build our
custom control we need to extend the WP_Customize_Control class where we override the function
render_content that displays the customizer.
Everything we push in an array to a control such as:
1
2
3

array(
"label" => "Some Text"
);

we can retrieve with


1

$this->label;

To extend the mentioned class we need to do something like this:


1
2
3
4
5
6
7

if (class_exists('WP_Customize_Control')) {
class WP_Customize_Category_Control extends WP_Customize_Control {
public function render_content() {
$this->label;
}
}
}

Here we are first checking if there even exists such class that we can extend because if there is maybe
an older version of WordPress which does not have the WordPress Customizer, this approach wont
show any errors or break the website since it did not pass the check and therefore nothing was called.

Custom Category Control


Lets create a file customizer_category.php and include it inside functions.php with:

Developing your custom control

27

include 'customizer_category.php';

Before we start developing our custom controls, lets create another section which will hold our
custom controls. After the line where we include the customizer_category.php, add this:
1
2
3
4
5
6
7
8
9
10
11
12
13

function wpcustomizer_thirdOption($wp_customize){
$wp_customize->add_section( 'section2' , array(
'title' => __( 'WP Customizer Custom Controls', 'your_wpcustomizer' ),
'priority' => 30,

) );

}
add_action('customize_register', 'wpcustomizer_thirdOption');

Now we have set our base so we can easily add new options which will use our custom controls.
In the file customizer_category.php write these:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

if (class_exists('WP_Customize_Control')) {
class WP_Customize_Category_Control extends WP_Customize_Control {
/**
* Render the control's content.
*
* @since 3.4.0
*/
public function render_content() {
$dropdown = wp_dropdown_categories(
array(
'name'
=> '_customize-dropdown-categories-' . $this->id,
'echo'
=> 0,
'show_option_none' => __( 'Select' ),
'option_none_value' => '0',
'selected'
=> $this->value(),
)
);
echo "<label>".$this->label."</label><br/>";
echo $dropdown;

Developing your custom control

20
21
22
23
24

28

}
}
}

Here we are getting all the categories by using the function wp_dropdown_categories and then we
are displaying first the label content and after that the dropdown. We are also selecting which
value is selected by passing the value of $this->value() to the parameter selected. To get this in
our customizer we need to make a new option.
In the file functions.php, inside the function wpcustomizer_thirdOption append this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

$wp_customize->add_setting( 'wpcustomizer[custom1]');
$wp_customize->add_control(
new WP_Customize_Category_Control(
$wp_customize,
'wpcustomizer[custom1]',
array(
'label'
=> 'Category',
'settings' => 'wpcustomizer[custom1]',
'section' => 'section2',
)
)
);

With this we made a new setting and mapped it with the section ID and the new control. Now we
have a dropdown where we can select a category. This can be useful if we are, for example, building
a theme and we have a section in our theme where the user of our theme could select from which
category to show recent posts.

29

Developing your custom control

Custom Category Control

If you have maybe noticed it, our category dropdown does not trigger the upper button to save &
publish our new change because it does not have such data in its attributes. To change this, before
displaying our label and dropdown add this:
1

$dropdown = str_replace( '<select', '<select ' . $this->get_link(), $dropdown );

Now the change will trigger also the upper button so we can save & publish our changes.

Custom Layout select


A very popular theme option is the layour chooser where we can have a layout for our blog or
archive template. In such option we choose to display the sidebar on the left or on the right.
To begin, lets create a new file customizer_layout.php and include it directly under the last include
and before the wpcustomizer_thirdOption().
Populate the customizer_layout.php with:
1
2
3
4
5
6
7
8
9
10
11

<?php
if (class_exists('WP_Customize_Control')) {
class WP_Customize_Layout_Control extends WP_Customize_Control {
/**
* Render the control's content.
*
* @since 3.4.0
*/
public function render_content() {

Developing your custom control

12
13
14
15
16
17
18
19
20
21
22
23
24

30

echo "<label><span class='customize-control-title'>".$this->label."</span>


</label>";
echo "<input ".checked( $this->value(), "left", false )." name='".
$this->id."' id='".$this->id."' type='radio' ". $this->get_link()."
value='left'> Left Sidebar<br/>";
echo "<input ".checked( $this->value(), "right", false )." name='".
$this->id."' id='".$this->id."' type='radio' ". $this->get_link()."
value='right'> Right Sidebar";

}
}
}

Here we are setting the label with a class customize-control-title which gives us a standard visual
style of the cutomizer titles and after that we are displaying two inputs with the same id and name
attributed but different values.
Open now the file functions.php and insert this into the function wpcustomizer_thirdOption:
1
2
3
4
5
6
7
8
9
10
11
12
13
14

$wp_customize->add_setting( 'wpcustomizer[custom2]');
$wp_customize->add_control(
new WP_Customize_Layout_Control(
$wp_customize,
'wpcustomizer[custom2]',
array(
'label'
=> 'Layout',
'settings' => 'wpcustomizer[custom2]',
'section' => 'section2',
)
)
);

If we are going to implement this we could for example use this such as:
1
2
3

$sidebarPosition = get_option("wpcustomizer");
get_template_part('content' 'sidebar_'.$sidebarPosition["custom2"]);

and then we get a template with our sidebar positions.

Developing your custom control

31

Custom Dynamic Layout Control


So what if we want to have a dynamic approach and want the layout control to be extendable by
our choices? In this chapter we will create a new dynamic control. Create a new file or even save
the customizer_layout.php as a new one with the name customizer_dynamic_layout.php. Include
it in functions.php above the function wpcustomizer_thirdOption:
1

include 'customizer_dynamic_layout.php';

The new file will have this code in it:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

<?php
if (class_exists('WP_Customize_Control')) {
class WP_Customize_Dynamic_Layout_Control extends WP_Customize_Control {
/**
* Render the control's content.
*
* @since 3.4.0
*/
public $choices = array("left" => "Left Sidebar", "right" => "Right sidebar");
public function __construct( $manager, $id, $args = array() ) {
$this->statuses = array( '' => __( 'Default', 'narga' ) );
if(!empty($args["choice"])){
$this->choices = $args["choice"];
}
parent::__construct( $manager, $id, $args );
}

public function render_content() {

echo "<label><span class='customize-control-title'>".$this->label."</span>


</label>";
if(is_array($this->choices)){
foreach ($this->choices as $key => $title) {
echo "<input ".checked( $this->value(), $key, false )." name='".
$this->id."' id='".$this->id."' type='radio' ".
$this->get_link()." value='".$key."'> ".$title."<br/>";

Developing your custom control

32
33
34
35
36
37
38
39
40
41
42
43
44

32

}
} else {
echo "<input ".checked( $this->value(), "left", false )." name='".
$this->id."' id='".$this->id."' type='radio' ". $this->get_link()."
value='left'> Left Sidebar<br/>";
echo "<input ".checked( $this->value(), "right", false )."
name='".$this->id."' id='".$this->id."' type='radio' ".
$this->get_link()." value='right'> Right Sidebar";
}

Here we are first setting a public variable choices that contains the default array with its values.
After that we are creating a magic function construct that uses the passed arguments (array) and
assigns the new choice to our variable if there are any. After that we are calling the parent class
which is WP_Customize_Control and its magic control construct so our class can be initialized and
our object created.
In our function render_content we are displaying the title of our control. After that we are checking
if the variable choices is actually an array and if it is not we are simply displaying the layout of two
radio buttons such as we did in the control WP_Customize_Layout_Control.
If the variable choices is an array then we are for each key/value pair constructing a radio button
with its value and text.
We can now call our new option with our dynamic choices such as:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

$wp_customize->add_setting( 'wpcustomizer[custom2]');
$wp_customize->add_control(
new WP_Customize_Dynamic_Layout_Control(
$wp_customize,
'wpcustomizer[custom2]',
array(
'label'
=> 'Layout',
'settings' => 'wpcustomizer[custom2]',
'section' => 'section2',
'choice'
=> array(
'left' => 'Left Sidebar',
'right' => 'Right Sidebar',
'none' => 'No Sidebar'
)

33

Developing your custom control

16
17
18

)
)
);

Custom Dynamic Layout Control

Using other resources to develop


WordPress has a very large community and due to that there are already plugins, frameworks or just
snippets of codes that can be implemented in your theme or plugin and enhance your WordPress
Customizer.

Paul Underwoods Custom Controls


Paul Underwood a.k.a. paulund has written a nice library of Custom Controls which you can use in
your development process. Its library is available on github: https://github.com/paulund/wordpresstheme-customizer-custom-controls.
So far this library consists of:

Category Dropdown - Creates a dropdown of all the categories on your WordPress theme.
Date Picker - Adds a date picker control to the theme customizer.
Layout Picker - Adds 3 images of layouts to the page for you to select a new style.
Menu Dropdown - Creates a dropdown of all the menus on your WordPress site.
Post Dropdown - Creates a dropdown of all the posts on your WordPress site.
Tags Dropdown - Creates a dropdown of all tags on your WordPress site.
Text Editor - Creates a textbox with the TinyMCE textarea.
Textarea - Creates a textarea input field
Taxonomy Dropdown - Creates a dropdown of taxonomies
User List Dropdown - Creates a dropdown of users for a role
Google Fonts Dropdown - Create a dropdown to show you the 30 most popular fonts on
Google web fonts

I recommend that anyone who wants to develop their own controls should look also into such
libraries as this one because they already have been checked and used by several people and I believe
that, atleast this library has a very good code standard which everyone can learn from.
https://github.com/paulund/wordpress-theme-customizer-custom-controls

35

Using other resources to develop

Kirki Plugin

Kirki Homepage

Kirki is a plugin that implements a new way of developing your Customizer Controls and by
developing I mean adding those types in your theme or plugin with just a few lines of code. You can
view all the documentation and implementation guides on their site: http://kirki.org/.
Example of usage (Kirki must be activated):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

<?php
/**
* Create the section
*/
function my_custom_section( $wp_customize ) {
// Create the "My Section" section
$wp_customize->add_section( 'my_section', array(
'title' => __( 'My Section', 'translation_domain' ),
'priority' => 12
) );
}
add_action( 'customize_register', 'my_custom_section' );
/**
* Create the setting
*/
http://kirki.org/

36

Using other resources to develop

16
17
18
19
20
21
22
23
24
25
26
27

function my_custom_setting( $controls ) {


$controls[] = array(
'type' => 'text',
'setting' => 'my_setting',
'label' => __( 'My custom control', 'translation_domain' ),
'section' => 'my_section',
'default' => 'some-default-value',
'priority' => 1,
);
return $controls;
}
add_filter( 'kirki/controls', 'my_custom_setting' );

Here we register a new section in the exact way as we do on our own. The second function is the
Kirki feature where we put a new control as an array and return it by adding this function on the
kirki/control filter. In this way we dont need to register a new setting because it is automatically
taken care of!

Titan Framework
Titan Framework is a framework that I have stumbled upon recently and I have automatically fell
in love with it because of its developer friendly documentation and implementation.

Titan Homepage

Their site is http://www.titanframework.net/. The framework can be embeded in your theme or


plugin or it can be installed as a stand-alone plugin. My recommendation is that you install this
http://www.titanframework.net/

Using other resources to develop

37

framework as a plugin from wordpress.org because then you will get all the new updates and bug
fixes without the need to enter in your theme or plugin and place the new code manually.
After you have installed or embed the titan framework you will have to write a function and hook
it onto the titan frameworks action like this:
1
2
3
4

add_action( 'tf_create_options', 'my_theme_create_options' );


function my_theme_create_options() {
// Initialize Titan & options here
}

Now you can start and create all the options you want.
Adding a section:
1
2
3
4

$titan = TitanFramework::getInstance( 'my-theme' );


$section = $titan->createThemeCustomizerSection( array(
'name' => 'My Section',
) );

We are creating the variable titan which we can use as a reference to a set of options (in this example
it is the my-theme ) and then create or retrieve options set by set.
Creating of a section is really easy and you can see it in the oneliner call above on the variable
section. Now we can use this variable as a reference to create options which will be under this
section. An option is created like this:
1
2
3
4
5
6

$section->createOption( array(
'name' => 'My Upload Option',
'id' => 'my_upload_option',
'type' => 'upload',
'desc' => 'Upload your image'
) );

and it is retrieved like this:


1
2

$titan = TitanFramework::getInstance( 'my-theme' );


$imageID = $titan->getOption( 'my_upload_option' );

Here we are also setting the variable titan which is a reference to the set of options by name mytheme. Now we just call the getOption where we pass the id of our customizer setting.
In the time of writing these controls/options for customizer could be made:

Using other resources to develop

38

Checkbox
Code
Color
Date
EDD License
Editor
Font
Multicheck
Multicheck Categories
Multicheck Pages
Multicheck Posts
Number
Radio
Radio Image
Radio Palette
Select
Select Categories
Select Google Fonts
Select Pages
Select Posts
Sortable
Text
Textarea
Upload

Plugin Customizer
Customizer Plugin is a tool built for WordPress Theme Developers and Plugin Developers. It extends
Customizer panel introduced in WP 3.4.
https://wordpress.org/plugins/customizer/

39

Using other resources to develop

Customizer WordPress Repository

With this plugin you can easily add sections and controls just by clicking on the Add buttons in
the Customizer Section.
Currently supported controls:

text standard input field


checkbox tick
color #RGB
image uses default WordPress media uploader
radio
select

También podría gustarte