42

Wp Customizer

Embed Size (px)

DESCRIPTION

Wp Customizer

Citation preview

Page 1: Wp Customizer
Page 2: Wp Customizer

Beginners’ guide to WordPress CustomizerLearn how customizer your themes with WordPressCustomizer

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 Publishingprocess. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools andmany iterations to get reader feedback, pivot until you have the right book and build traction onceyou do.

©2014 - 2015 Igor Benić

Page 3: Wp Customizer

Contents

Prologue . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

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

WordPress Customizer 101 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3Where can I find WordPress Customizer? . . . . . . . . . . . . . . . . . . . . . . . . . . . 3How to use WordPress Customizer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4WordPress Customizer Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

Developing your Theme Customizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9How to define a Customizer Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9Defining a Panel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Registering our Customizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11Setting our Child theme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Create your first Customizer Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13Creating our first section with options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

Developing your custom control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26How to develop a custom control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Custom Category Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Custom Layout select . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Custom Dynamic Layout Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

Using other resources to develop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Paul Underwoods‘ Custom Controls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Kirki Plugin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Titan Framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Plugin Customizer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

Page 4: Wp Customizer

PrologueWordPress is a very popular CMS in the world of websites. In its previous version 3.4., WordPressintroduced a new way of designing and configuring a theme without the need of developing andusing Settings API. This new way provided us with a real example so we can see how the changeswill affect are website and if we dont like it or it breaks up our website we can just easily click onCancel.

This new way of customizing our themes is calledWordPress Customizer.

Page 5: Wp Customizer

Who is this book for?Beginner‘s guide to WordPress Customizer is written for all beginners and skilled developers whowant to find out how to use WordPress Customizer, develop options for it and even create custominput controls.

You will learn the basics of WordPress Customizer and how it operates. You will also learn how toenable a Live preview of WordPress Customizer and how to implement it into your themes (existingor under development).

Page 6: Wp Customizer

WordPress Customizer 101In 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, Sidebarand 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 yourtheme appear and here you can change the provided settings and look how the changes appear onyou theme.

Customizer Page

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

Page 7: Wp Customizer

WordPress Customizer 101 4

How to use WordPress Customizer?

WordPress Customizer is fairly easy to use and it provides options that are really intuitive/familiarso the users won’t and shouldn’t 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 andour site on the right. The sections and options depend on the theme we are using and its Customizerdefined settings that are set through the code.

Page 8: Wp Customizer

WordPress Customizer 101 5

Customizer Panel

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

Page 9: Wp Customizer

WordPress Customizer 101 6

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 waysor 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 sidewill refresh and show the changed data, but if it is set on live, we will see the change as we changethe data without the need to refresh. The later requires a bit of javascript to be able to operate andchange the data.

When we are done with all the changes and we are happy how our website looks and feels, we canpublish 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 becausewe can picture all the parts in our head. WordPress Customizer consists of:

1. Panels2. Sections3. Settings4. Controls

Page 10: Wp Customizer

WordPress Customizer 101 7

Customizer Panels

Panels were introduced in WordPress 4.0 and they are the containers of sections. We can useCustomizer Panels to better organize the WordPress Customizer for our theme and therefore makeit even easier for a regular user to distinguish between regular Customizer settings and the currentthemes‘ Customizer settings.

Customizer Panels

To distinguish panels from regular sections in Customizer, they are presented with a different arrowon the right side of the panel. Arrow that is representing a new panel is oriented horizontally, thuspointing 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 becollapsed and uncollapsed to show the available controls under the chosen section.

Page 11: Wp Customizer

WordPress Customizer 101 8

Collapsed Section

Customizer Settings

When talking about settings in WordPress Customizer we are actually referring to the values thatare inserted and saved in the database. Those options can be easily retrieved by using WordPressAPI 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 auser 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 controlsthat are used to control the design, content or even functionality of the theme.

¹http://codex.wordpress.org/Class_Reference/WP_Customize_Manager/add_control

Page 12: Wp Customizer

Developing your Theme CustomizerIn this section we will make additional WordPress Customizer sections, controls and option upona child theme. We will use a child theme so we don‘t interfere with the functionality of the parenttheme. In this way we can add other WordPress Customizer settings just by extending the parenttheme with our child theme.

How to define a Customizer Option

The Customizer Option is defined by several parts. The definition contains the value (setting), sectionin which it is presented and the control which is used to output the input for this option.

Let‘s do it in that order.

Defining the setting

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

2 'default' => 'Starting Value',

3 'transport' => 'refresh or postMessage',

4 'type' => 'option or theme_mod',

5 'capability' => 'ex. manage_options | show this option only to the users

6 with this capabaility'

7 'theme_supports' => 'show this option if the theme supports a theme feature',

8 'sanitize_callback' => 'function to validate the input',

9 'sanitize_js_callback' => 'function to check the value given by database to

10 customizer'

11 ) );

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 definedwithinWordPressCustomizer. If wewant to develop a set of optionswhich are referring only to our theme or somethingsimilar, we can then define another section to group them separately from other options.

Page 13: Wp Customizer

Developing your Theme Customizer 10

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

2 'title' => __( 'Section Title', 'wp_localize' ),

3 'priority' => 30,

4 'description' => __('Section Description', 'wp_localize'),

5 'panel_id' => 'panel_id'

6 ) );

The priority parameter defines the position of the section among other sections. The parameterpanel_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 notneed 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 sectiondoes a setting apear and in which way (input type).

1 $wp_customize->add_control(

2 new WP_Customize_Control(

3 $wp_customize,

4 'control_id',

5 array(

6 'label' => __( 'Control Text', 'wp_localize' ),

7 'section' => 'section_id',

8 'settings' => 'setting_id',

9 'active_callback' => 'is_front_page', //ex. show this only on front page

10 'type' => 'text, textarea, checkbox, radio, select or dropdown-pages',

11 //If radio or select is selected then we need also choices

12 'choices' => array(

13 'dark' => __( 'Dark' ),

14 'light' => __( 'Light' )

15 ),

16

17 ),

Page 14: Wp Customizer

Developing your Theme Customizer 11

18 'input_attrs' => array(

19 'min' => 0,

20 'max' => 10,

21 'step' => 2,

22 'class' => 'test-class test',

23 'style' => 'color: #0a0',

24 ),

25 )

26 );

The parameters active_callback and input_attrs are avaiable fromWordPress 4.0 and above. All theattributes defined in the parameter input_attrs are then displayed in the element input as attributes.

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

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

Type textarea is available from WordPress 4.0 and above. For any type of input that uses an inputelement, 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. CustomizerPanels were introduced in WordPress 4.0 so before that you cannot use them.

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

2 'priority' => 10,

3 'capability' => 'edit_theme_options',

4 'theme_supports' => '',

5 'title' => '',

6 'description' => '',

7 ) );

Registering our Customizer

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

Page 15: Wp Customizer

Developing your Theme Customizer 12

1 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. Goto the folder of themes which is generally your_wordpress_installation/wp-content/themes/. Createa new folder called twentyfourteen-child and make a file style.css with this content:

1 /*

2 Theme Name: Twenty Fourteen Child

3 Theme URI: http://example.com/twenty-fourteen-child/

4 Description: Twenty Fourteen Child Theme

5 Author: John Doe

6 Author URI: http://example.com

7 Template: twentyfourteen

8 Version: 1.0.0

9 Tags: light, dark, two-columns, right-sidebar, responsive-layout,

10 accessibility-ready

11 Text Domain: twenty-fourteen-child

12 */

13

14 @import url("../twentyfourteen/style.css");

15

16 /* =Theme customization starts here

17 -------------------------------------------------------------- */

With the line @import we are using the default style from the parent theme and by that we don‘tneed to develop a custom theme css.

After that you have saved your style.css create another file functions.php. This file will be usedto develop our WordPress Customizer for our child theme. The child theme calls and uses thefunctions.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 toextend the current WordPress Customizer settings by adding additional controls or even sectionsand panels.

In the functions.php add just one line:

1 <?php

Page 16: Wp Customizer

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 tothe color section in WordPress Customizer.

If we are to follow the order described in previous sections we will define the inital setting first. Letsdefine our function that will be hooked and registered to WordPress customizer with its setting,section and control.

1 function wpcustomizer_firstOption($wp_customize){

2 //Here goes our code

3 }

4

5 add_action('customize_register', 'wpcustomizer_firstOption');

We will now define a new setting that will be called wpcustomizer[Color] and it will be used toset a new background color of the entire web site. That means that the color will be added to theelement body through CSS. We are defining this options as an array because then we can defineseveral options by one name such as wpcustomizer and each particular option will be saved undera 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 $wp_customize->add_setting( 'wpcustomizer[Color]' , array(

2 'default' => '#ffffff',

3 'transport' => 'postMessage',

4 'type' => 'option',

5 'capability' => 'manage_options'

6

7 )

8 );

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

After the defined setting define a new control and connect the settingwith the section by this control.

Page 17: Wp Customizer

Developing your Theme Customizer 14

1 $wp_customize->add_control(

2 new WP_Customize_Color_Control(

3 $wp_customize,

4 'wpcustomizer[Color]',

5 array(

6 'label' => __( 'Background Color by WpCustomizerOption',

7 'your_wpcustomizer' ),

8 'section' => 'colors',

9 'settings' => 'wpcustomizer[Color]',

10 ) )

11 );

What have we done until now? We have defined a new setting which its change will be viewedand seen instantly without the need to refresh the window (transport ⇒ postMessage). We havealso defined it as an option since I have encountered a problem with saving and retrieving the valuefrom theme_mod.

After our setting defined we have defined a Customizer Control that represent a colorwheel wherewe 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 itnow. After that go to the customizer by following this path Appearance > Customize. You shouldsee 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.

Page 18: Wp Customizer

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, letsenqueue it so it will be called on the preview of Customizer. Write this at the end of the functions.phpfile:

1 function wpcustomizer_live_preview()

2 {

3 wp_enqueue_script(

4 'wpcustomizer-myjs', //Give the script an ID

5 get_stylesheet_directory_uri().'/customizer.js',//Point to file

6 array( 'jquery','customize-preview' ), //Define dependencies

7 '', //Define a version (optional)

8 true //Put script in footer?

9 );

10 }

11 add_action( 'customize_preview_init', 'wpcustomizer_live_preview' );

Here we have enqueued our javascript file so that our functions in javascript are called and processedin the preview of our theme (in Customizer). Now we can write our code so that our elements willchange as we change them by, for example, changing the color. Go to the customizer.js file and writenext:

1 ( function( $ ) {

2

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

4 value.bind( function( newval ) {

5 $('body').css('backgroundColor', newval );

6 } );

7 } );

8

9 } )( jQuery );

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

Page 19: Wp Customizer

Developing your Theme Customizer 16

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 coloryou 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 alsoon the front web and present it to our users who are viewing our site, we need to define anotherfunction 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:

Page 20: Wp Customizer

Developing your Theme Customizer 17

1 function wpcustomizer_css()

2 {

3 $ourCustomizerOptions = get_option('wpcustomizer');

4 ?>

5 <style type="text/css">

6 body {

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

8 }

9 </style>

10 <?php

11 }

12 add_action( 'wp_head', 'wpcustomizer_css');

We have defined a function which at the beginning gets our optionwpcustomizer and since we havedefined our first option to be just a part of this option array we will access our value by using the callourCustomizerOptions[“Color”]. We are then writing a standard style element to write some CSS init. We have defined here a CSS rule to set the background color of the body to the newly savedvalue. By hooking this function to the wp_head we ensure that this piece of code will be executedand 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 optionto upload an image. This image will be displayed as a background image since we are using thetwentyfourteen theme look and feel we have only the right side available to do such thing. The otheroption will be a radio button that will give us a choice to have the background image positioned ontop, 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 function wpcustomizer_secondOption($wp_customize){

2

3 $wp_customize->add_section( 'sectionExampleID' , array(

4 'title' => __( 'WP Customizer Section', 'your_wpcustomizer' ),

5 'priority' => 30,

6 'description' => __('This is an example of a section',

7 'your_wpcustomizer'),

8

9 ) );

10

11

12 }

Page 21: Wp Customizer

Developing your Theme Customizer 18

13

14 add_action('customize_register', 'wpcustomizer_secondOption');

Here we have defined our section with an id sectionExampleID and we named itWP CustomizerSection. Now, after the section definition add a setting (inside the function wpcustomizer_secon-dOption.

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

2 'default' => '',

3 'transport' => 'postMessage',

4 'type' => 'option',

5 'capability' => 'manage_options'

6

7 )

8 );

With this code we have defined a new setting which is saved also in the wpcustomizer option thatwe started using in the last chapter. Now we are saving another setting with the key Image. The lastthing we have to set is a control to upload the image.

1 $wp_customize->add_control(

2 new WP_Customize_Image_Control(

3 $wp_customize,

4 'wpcustomizer[Image]',

5 array(

6 'label' => __( 'Background Image by WpCustomizerOption',

7 'your_wpcustomizer' ),

8 'section' => 'sectionExampleID',

9 'settings' => 'wpcustomizer[Image]',

10 ) )

11 );

This is a new controlWP_Customize_Image_Control.With this control wewill have a form to uploadan image and use that image for our background image.We have assigned the new sectionwe createdwith the new setting. Now if you open up the WordPress Customizer in your localhost or a site youare developing you will see this new section and the form to upload the image.

Page 22: Wp Customizer

Developing your Theme Customizer 19

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 withthis control. To show this image we will use a function which we have defined when we created ourfirst option. Go to the file customizer.js so we can set a live preview of the image before we go andset the CSS that is used for the live site. After the defined javascript for the option Color, set this:

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

2 value.bind( function( newval ) {

3 $('body').css('backgroundImage', 'url("'+newval+'")' );

4 } );

5 } );

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

Page 23: Wp Customizer

Developing your Theme Customizer 20

Customizer Image Control

Page 24: Wp Customizer

Developing your Theme Customizer 21

Let‘s implement also the actual saved value on the true version of our site. This will be done byadding 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 theyare the same, so our style element should look like this:

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

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

3 }

So what if we uploaded a really small image? What if we want to make a possibility for the user ofour theme to set a small image with a position of top right? This can all be done with the CustomizerControls 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 andrepeat. Lets define our setting. Inside the function wpcustomizer_secondOption insert this:

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

2 'default' => 'no-repeat',

3 'transport' => 'postMessage',

4 'type' => 'option',

5 'capability' => 'manage_options'

6

7 )

8 );

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

Page 25: Wp Customizer

Developing your Theme Customizer 22

1 $wp_customize->add_control(

2 'wpcustomizer[ImageRepeat]',

3 array(

4 'type' => 'radio',

5 'label' => 'Image placement',

6 'section' => 'sectionExampleID',

7 'choices' => array(

8 'no-repeat' => 'No Repeat',

9 'repeat' => 'Repeat',

10 'repeat-x' => 'Repeat X',

11 'repeat-y' => 'Repeat Y',

12 ),

13 )

14 );

We have asigned a Customizer Control to our newly added section and to our option. This controlhas a different key value in its array which is a requirement when we are setting the control to typeradio. 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 settingto show the actual image on the front side of our website. Now we will do the opposite and we willfirst 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 seeanything because the image starts from left-to-right and therefore you cannot see it since it is placedbehind 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 usedwith the last options and just change the appropriate value, so lets open the file customizer.js andadd the following under the last option:

Page 26: Wp Customizer

Developing your Theme Customizer 23

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

2 value.bind( function( newval ) {

3 $('body').css('backgroundRepeat', newval );

4 } );

5 } );

Now the image will be placed/shown differently everytime you choose another value for therepeating option.

So now we can change the repeating of our image, but what if we want to have a non repeatingimage 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 wherewe could define one option which will give us information on which value will we use and anotherwhere we store the value or we could define on option as a text input where we could insert ourdesired position and then show it in CSS.

By doing this, we should have also a callback functionwhichwill check the input value and configureit if possible. Let‘s do that. In the functions.php add another setting:

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

2 'default' => 'top right',

3 'transport' => 'postMessage',

4 'type' => 'option',

5 'capability' => 'manage_options',

6 'sanitize_callback' => 'check_position'

7 )

8 );

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

Page 27: Wp Customizer

Developing your Theme Customizer 24

1 $wp_customize->add_control(

2 'wpcustomizer[ImagePosition]',

3 array(

4 'type' => 'text',

5 'label' => 'Position value (y x). Can be set as

6 percentage (40%), number in pixels (23px) or even text

7 (center,top,bottom,left,right)',

8 'section' => 'sectionExampleID',

9

10

11 )

12 );

With this we can now set the various positions for the image. Before we do that we need to defineour callback function so outside the function we need to define another function. Add this to thebottom of functions.php:

1 function check_position($input){

2 $string = trim($input);

3

4 if (strpos($string, ' ') !== false) {

5 //We have two words

6 $string = strip_tags($string);

7 return $string;

8 }

9

10 return "top right";

11 }

We trim the input we get before WordPress saves it in the database. We then check if there is a spacein the string which means that there are actually two or more words. If that is not right the functionreturns our default value top right. If the input contains two words they will be stripped of tags sothere 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 ourfile customizer.js and before

1 } )( jQuery );

insert this:

Page 28: Wp Customizer

Developing your Theme Customizer 25

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

2 value.bind( function( newval ) {

3 $('body').css('backgroundPosition', newval );

4 } );

5 } );

Here we are now getting the new value and setting it as a CSS property (background-position) ofthe body element.

After that we just need to set also a CSS property which will be rendered when the page is requested.Let‘s go back to the file functions.php and in the function wpcustomizer_css, inside the bodyelement 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.

Page 29: Wp Customizer

Developing your custom controlIn this part of our development chapter we will learn how to develop our own customizer controlswhich 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 itdoes not actually require any knowledge of OOP since we will just follow a pattern. To build ourcustom control we need to extend the WP_Customize_Control class where we override the functionrender_content that displays the customizer.

Everything we push in an array to a control such as:

1 array(

2 "label" => "Some Text"

3 );

we can retrieve with

1 $this->label;

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

1 if (class_exists('WP_Customize_Control')) {

2 class WP_Customize_Category_Control extends WP_Customize_Control {

3 public function render_content() {

4 $this->label;

5 }

6 }

7 }

Here we are first checking if there even exists such class that we can extend because if there is maybean older version of WordPress which does not have the WordPress Customizer, this approach wontshow 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:

Page 30: Wp Customizer

Developing your custom control 27

1 include 'customizer_category.php';

Before we start developing our custom controls, let‘s create another section which will hold ourcustom controls. After the line where we include the customizer_category.php, add this:

1 function wpcustomizer_thirdOption($wp_customize){

2

3 $wp_customize->add_section( 'section2' , array(

4 'title' => __( 'WP Customizer Custom Controls', 'your_wpcustomizer' ),

5 'priority' => 30,

6

7

8 ) );

9

10

11 }

12

13 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 if (class_exists('WP_Customize_Control')) {

2 class WP_Customize_Category_Control extends WP_Customize_Control {

3 /**

4 * Render the control's content.

5 *

6 * @since 3.4.0

7 */

8 public function render_content() {

9 $dropdown = wp_dropdown_categories(

10 array(

11 'name' => '_customize-dropdown-categories-' . $this->id,

12 'echo' => 0,

13 'show_option_none' => __( 'Select' ),

14 'option_none_value' => '0',

15 'selected' => $this->value(),

16 )

17 );

18 echo "<label>".$this->label."</label><br/>";

19 echo $dropdown;

Page 31: Wp Customizer

Developing your custom control 28

20

21

22 }

23 }

24 }

Here we are getting all the categories by using the function wp_dropdown_categories and then weare displaying first the label content and after that the dropdown. We are also selecting whichvalue is selected by passing the value of $this->value() to the parameter selected. To get this inour customizer we need to make a new option.

In the file functions.php, inside the function wpcustomizer_thirdOption append this:

1 $wp_customize->add_setting( 'wpcustomizer[custom1]');

2

3 $wp_customize->add_control(

4 new WP_Customize_Category_Control(

5 $wp_customize,

6 'wpcustomizer[custom1]',

7 array(

8 'label' => 'Category',

9 'settings' => 'wpcustomizer[custom1]',

10 'section' => 'section2',

11

12 )

13 )

14 );

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

Page 32: Wp Customizer

Developing your custom control 29

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, beforedisplaying 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 orarchive 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 includeand before the wpcustomizer_thirdOption().

Populate the customizer_layout.php with:

1 <?php

2

3 if (class_exists('WP_Customize_Control')) {

4 class WP_Customize_Layout_Control extends WP_Customize_Control {

5 /**

6 * Render the control's content.

7 *

8 * @since 3.4.0

9 */

10 public function render_content() {

11

Page 33: Wp Customizer

Developing your custom control 30

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

13 </label>";

14 echo "<input ".checked( $this->value(), "left", false )." name='".

15 $this->id."' id='".$this->id."' type='radio' ". $this->get_link()."

16 value='left'> Left Sidebar<br/>";

17 echo "<input ".checked( $this->value(), "right", false )." name='".

18 $this->id."' id='".$this->id."' type='radio' ". $this->get_link()."

19 value='right'> Right Sidebar";

20

21

22 }

23 }

24 }

Here we are setting the label with a class customize-control-title which gives us a standard visualstyle of the cutomizer titles and after that we are displaying two inputs with the same id and nameattributed but different values.

Open now the file functions.php and insert this into the function wpcustomizer_thirdOption:

1 $wp_customize->add_setting( 'wpcustomizer[custom2]');

2

3 $wp_customize->add_control(

4 new WP_Customize_Layout_Control(

5 $wp_customize,

6 'wpcustomizer[custom2]',

7 array(

8 'label' => 'Layout',

9 'settings' => 'wpcustomizer[custom2]',

10 'section' => 'section2',

11

12 )

13 )

14 );

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

1 $sidebarPosition = get_option("wpcustomizer");

2

3 get_template_part('content' 'sidebar_'.$sidebarPosition["custom2"]);

and then we get a template with our sidebar positions.

Page 34: Wp Customizer

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 byour choices? In this chapter we will create a new dynamic control. Create a new file or even savethe customizer_layout.php as a new one with the name customizer_dynamic_layout.php. Includeit in functions.php above the function wpcustomizer_thirdOption:

1 include 'customizer_dynamic_layout.php';

The new file will have this code in it:

1 <?php

2

3 if (class_exists('WP_Customize_Control')) {

4 class WP_Customize_Dynamic_Layout_Control extends WP_Customize_Control {

5 /**

6 * Render the control's content.

7 *

8 * @since 3.4.0

9 */

10 public $choices = array("left" => "Left Sidebar", "right" => "Right sidebar");

11

12 public function __construct( $manager, $id, $args = array() ) {

13 $this->statuses = array( '' => __( 'Default', 'narga' ) );

14 if(!empty($args["choice"])){

15 $this->choices = $args["choice"];

16 }

17 parent::__construct( $manager, $id, $args );

18 }

19

20

21 public function render_content() {

22

23

24

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

26 </label>";

27 if(is_array($this->choices)){

28 foreach ($this->choices as $key => $title) {

29 echo "<input ".checked( $this->value(), $key, false )." name='".

30 $this->id."' id='".$this->id."' type='radio' ".

31 $this->get_link()." value='".$key."'> ".$title."<br/>";

Page 35: Wp Customizer

Developing your custom control 32

32 }

33 } else {

34 echo "<input ".checked( $this->value(), "left", false )." name='".

35 $this->id."' id='".$this->id."' type='radio' ". $this->get_link()."

36 value='left'> Left Sidebar<br/>";

37 echo "<input ".checked( $this->value(), "right", false )."

38 name='".$this->id."' id='".$this->id."' type='radio' ".

39 $this->get_link()." value='right'> Right Sidebar";

40

41 }

42

43

44 }

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) andassigns the new choice to our variable if there are any. After that we are calling the parent classwhich is WP_Customize_Control and its magic control construct so our class can be initialized andour object created.

In our function render_content we are displaying the title of our control. After that we are checkingif the variable choices is actually an array and if it is not we are simply displaying the layout of tworadio buttons such as we did in the controlWP_Customize_Layout_Control.

If the variable choices is an array then we are for each key/value pair constructing a radio buttonwith its value and text.

We can now call our new option with our dynamic choices such as:

1 $wp_customize->add_setting( 'wpcustomizer[custom2]');

2

3 $wp_customize->add_control(

4 new WP_Customize_Dynamic_Layout_Control(

5 $wp_customize,

6 'wpcustomizer[custom2]',

7 array(

8 'label' => 'Layout',

9 'settings' => 'wpcustomizer[custom2]',

10 'section' => 'section2',

11 'choice' => array(

12 'left' => 'Left Sidebar',

13 'right' => 'Right Sidebar',

14 'none' => 'No Sidebar'

15 )

Page 36: Wp Customizer

Developing your custom control 33

16 )

17 )

18 );

Custom Dynamic Layout Control

Page 37: Wp Customizer

Using other resources to developWordPress has a very large community and due to that there are already plugins, frameworks or justsnippets of codes that can be implemented in your theme or plugin and enhance your WordPressCustomizer.

Paul Underwoods‘ Custom Controls

Paul Underwood a.k.a. paulund has written a nice library of Custom Controls which you can use inyour development process. Its library is available on github: https://github.com/paulund/wordpress-theme-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 onGoogle web fonts

I recommend that anyone who wants to develop their own controls should look also into suchlibraries as this one because they already have been checked and used by several people and I believethat, atleast this library has a very good code standard which everyone can learn from.

²https://github.com/paulund/wordpress-theme-customizer-custom-controls

Page 38: Wp Customizer

Using other resources to develop 35

Kirki Plugin

Kirki Homepage

Kirki is a plugin that implements a new way of developing your Customizer Controls and bydeveloping I mean adding those types in your theme or plugin with just a few lines of code. You canview all the documentation and implementation guides on their site: http://kirki.org/³.

Example of usage (Kirki must be activated):

1 <?php

2 /**

3 * Create the section

4 */

5 function my_custom_section( $wp_customize ) {

6 // Create the "My Section" section

7 $wp_customize->add_section( 'my_section', array(

8 'title' => __( 'My Section', 'translation_domain' ),

9 'priority' => 12

10 ) );

11 }

12 add_action( 'customize_register', 'my_custom_section' );

13 /**

14 * Create the setting

15 */

³http://kirki.org/

Page 39: Wp Customizer

Using other resources to develop 36

16 function my_custom_setting( $controls ) {

17 $controls[] = array(

18 'type' => 'text',

19 'setting' => 'my_setting',

20 'label' => __( 'My custom control', 'translation_domain' ),

21 'section' => 'my_section',

22 'default' => 'some-default-value',

23 'priority' => 1,

24 );

25 return $controls;

26 }

27 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 theKirki feature where we put a new control as an array and return it by adding this function on thekirki/control filter. In this way we dont need to register a new setting because it is automaticallytaken care of!

Titan Framework

Titan Framework is a framework that I have stumbled upon recently and I have automatically fellin 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 orplugin or it can be installed as a stand-alone plugin. My recommendation is that you install this

⁴http://www.titanframework.net/

Page 40: Wp Customizer

Using other resources to develop 37

framework as a plugin from wordpress.org because then you will get all the new updates and bugfixes 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 hookit onto the titan frameworks‘ action like this:

1 add_action( 'tf_create_options', 'my_theme_create_options' );

2 function my_theme_create_options() {

3 // Initialize Titan & options here

4 }

Now you can start and create all the options you want.

Adding a section:

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

2 $section = $titan->createThemeCustomizerSection( array(

3 'name' => 'My Section',

4 ) );

We are creating the variable titanwhich we can use as a reference to a set of options (in this exampleit 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 variablesection. Now we can use this variable as a reference to create options which will be under thissection. An option is created like this:

1 $section->createOption( array(

2 'name' => 'My Upload Option',

3 'id' => 'my_upload_option',

4 'type' => 'upload',

5 'desc' => 'Upload your image'

6 ) );

and it is retrieved like this:

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

2 $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 my-theme. 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:

Page 41: Wp Customizer

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 forWordPress ThemeDevelopers and PluginDevelopers. It extendsCustomizer panel introduced in WP 3.4.

⁵https://wordpress.org/plugins/customizer/

Page 42: Wp Customizer

Using other resources to develop 39

Customizer WordPress Repository

With this plugin you can easily add sections and controls just by clicking on the “Add” buttons inthe Customizer Section.

Currently supported controls:

• text – standard input field• checkbox – tick• color – #RGB• image – uses default WordPress media uploader• radio• select