Making a custom control for the Theme Customizer
Okay, a quick one today. Let’s make a custom control for the customizer.
Back in the first tutorial, I talked about the various controls available in the customizer. Specifically I mentioned image handling, color wheels, text boxes, radios, dropdowns, and checkboxes.
Let’s try a new one? How about a textarea? It’s not in the core code, but it’s easy enough to add one.
Create a Class
So first, we have to create our class. Now, where we create this class is important. Specifically, we have to create it in the function called by the customize_register action. You remember that, right? It started like this:
add_action( 'customize_register', 'themename_customize_register' ); function themename_customize_register($wp_customize) { // ... do stuff ...
The reason we have to create our class in here is because we need to make our new class extend the built in WP_Customize_Control class, and that class only gets loaded and defined when we’re actually using the customizer. An alternate means of doing this would be to wrap the class definition in an “if (class_exists(‘WP_Customize_Control’))” statement, if you prefer to not have your classes defined inside a function. Personal preference, I don’t think it makes a difference either way.
So, here’s our textarea control. All we’re doing is to override the render_content() function and make it display a textarea.
class Example_Customize_Textarea_Control extends WP_Customize_Control { public $type = 'textarea'; public function render_content() { ?> <label> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <textarea rows="5" style="width:100%;" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea> </label> <?php } }
You can see how simple it is to do, really. We just output a span with the value from $this->label for the name displayed above the textarea, then output the textarea itself.
Note that the textarea has no “name” parameter. It doesn’t need one. The $this->link() function outputs the information for the customizer script. Specifically, it will create a “data-customizer-setting-link” attribute, to link the textarea to the proper setting it’s controlling.
Now, we just have to use the new control.
Add a setting and control
Let’s go back to the theme demo I used in the second customizer tutorial post, and add a new setting and control to demonstrate this:
$wp_customize->add_setting( 'textarea_setting', array( 'default' => 'Some default text for the textarea', ) ); $wp_customize->add_control( new Example_Customize_Textarea_Control( $wp_customize, 'textarea_setting', array( 'label' => 'Textarea Setting', 'section' => 'themedemo_demo_settings', 'settings' => 'textarea_setting', ) ) );
Nothing complicated there. We create the setting, then we create our control, using the new class we made for this purpose earlier.
Use the setting in the theme
Now let’s add to that index.php file I made in the theme demo to show the results of our work.
echo 'textarea_setting => '.get_theme_mod( 'textarea_setting', 'default_value' )."\n";
And that’s pretty much that. We now have a textarea control, and changing/saving results in the setting changing as well.
You can extend this further to use postMessage for real-time changing of settings, if you like.
Custom controls using complex javascript and such can be done as well. Examine the core WP_Customize_Color_Control, which uses the farbtastic Javascript for the color wheel. That one has special JS in the customize-controls.dex.js file to handle receiving the input and passing it along to the customizer JS. Look for “api.ColorControl” and how it gets the setting from the HTML and sets it. I’m not a JS guru, that sort of thing is slightly outside my own scope. 🙂
Any ideas for other controls that themes might need? Leave a comment, maybe somebody has a solution.
Amazing tutorial, thanks for it. In my opinion, the next tutorial should be about adding more advanced controls to the theme cusomizer, such as sortable slider manager.
You can use the jQuery UI library:
http://jqueryui.com/demos/sortable/#placeholder
Here’s simple documentation of options panel framework, in the bottom of article, there is the slider array structure:
http://aquagraphite.com/2011/11/smof-documentation/
This would be a very practical feature!
exactly, that would be awesome
I wonder if anyone already discovered how to do that. I really need it, that would be awesome!
Working on it! 😉
Hey Otto,
thanks for your informative tutorials!
I’m currently facing a strange issue:
If I add more than 5 settings/controls to one section, the order of the controls gets mixed (http://wordpress.stackexchange.com/questions/61321/theme-customizer-settings-order)
Maybe you can bring in some light on this one?
Thanks!
If you need them in a specific order, then give a priority value to the controls. Otherwise, their order is not defined and cannot be guaranteed.
Hi Otto, just wondering since we are on the topic of customizing, can use a conditional to display a section only on a particular page?
No, because the controls are outside of the content of the page itself. The page is loaded in a frame inside the control system.
Ran some test myself and got that much figured out, Thanks for the reply…
Thanks for the well written article! I actually used it to create a taxonomy dropdown control for the theme customizer: http://ericjuden.com/2012/08/custom-taxonomy-control-for-the-theme-customizer/
Eric
Otto, couple of questions
– Validation, how is validation being handled?
– Whats the risk of using something like the wp_editor for html markup?
Shawn
I don’t know about the wp_editor, actually. Haven’t tried.
Validation is handled in the same way as everything else. If you’re using register_setting() to make the setting, then the validation function you declare there will be called when the customizer controls are saved, because the validation function hooks in at the sanitize_option level (as a filter, actually). So any case where the option is set triggers the validation.
If you use the theme_mod system, there is no inherent validation other than the base-sanitization which is built into all options mechanisms, which means you’d need to roll your own if you need more than simple database sanitization. Theme mods are actually stored as an option, using the theme_mods_$themeslug option name, so you could roll a validation filter for them by hooking a function to ‘sanitize_option_theme_mods_’ . get_option( ‘stylesheet’ ), and checking the resulting array of values to validate each entry. At the end of your function, you return the complete array.
I tried the wp_editor() and got some errors one in particular; the $this->link() is echoed and could not be used in the wp_editor settings array(), I did not really go beyond that…
Since I’m using the theme_mod option, I would imagine (could not find where) set_theme_mod() handles saving the value(s) which using update_option() and passes validation to
apply_filters("sanitize_option_{$option}", $value, $option);
in the sanitize_option function, if this is what you are referring to then I would need to add a sanitize_option_name filter, right?If you’re using theme mods, then you attach your validation function to sanitize_option_theme_mods_THEMESLUG like I said before. Like this:
Like that. Theme mods are saved as a single array of options under theme_mod_THEMESLUG, where themeslug is the theme’s name. get_option(‘stylesheet’) gets the current theme’s slug, but that won’t work unless your theme is the active theme, I think. Still, you know what your theme’s slug is and can likely hardcode it for the time being. I bet there’s a programmatic way to get it too. I’d have to look at the code a bit more to find the “right” way.
Amazing! Thanks for this tutorial i was looking how to create textarea in customizer and here it is. Thank You!
Hello Otto (& other readers)
I’ve made a custom control that creates a slider with jquery-ui slider.
It works perfectly as in: when I slide, it updates the value in the corresponding text input field.
Sadly, the value doesn’t update the live preview.
When I manually update the value in the text input, it does update correctly.
Got that part working, thanks to your tutorials!
Can you tell me how to bind the new value created by the jquery ui slider to the preview window?
Or maybe a clue where to start?
Thanks allot!
Greets, Sander
I’ve found an answer to my question.. Just needed to load the slider after the iframe was loaded. So simple, works perfect!
Hi Sander,
I facing a same issue. I can not update on live preview.
Could you please help me on this?
Thanks,
Prayas
Hi,
Thanks you very much for your tutorial.
I tried to use Jquery UI slider inside a customize controller. But it doesn’t load jquery ui and I’m getting “Uncaught TypeError: Object [object Object] has no method ‘slider'” in JS console.
Here is my code.
class Slider_Control extends WP_Customize_Control{
public $type = 'slider';
public function render_content(){
?>
label); ?>
Value: value; ?>
<input type="hidden" value="value; ?>" />
jQuery(function(){
jQuery('.slider').slider();
});
<?php
}
}
and action in function.php to load jquery ui
function my_admin_scripts(){
wp_enqueue_script('jquery-ui-slider');
}
add_action('admin_enqueue_scripts', 'my_admin_scripts');
Any help is highly appreciate.
Thanks.
Sorry, something wrong with formatting. Please got to http://pastebin.com/dBnxyb1N
Hi Gihan,
Add a function called ‘enqueue’ to your Slider_Control class that contain the wp_enqueue_script calls.
Like:
public function enqueue()
{
wp_enqueue_script( 'jquery-ui-slider' );
}
@Sander & @Gihan – did you figure this out. I was attempting to use Gihan’s code but his attempt at using the `admin_enqueue_scripts` is not correct (at least not with WP 3.5.1) because it doesn’t even register in the theme-customizer area. @Sander you corrected his usage of wp_enqueue_script to be inside the Slider_Control class, but I just can’t find the correct hook for this… I think it’s not very well documented yet, perhaps?
Here’s my Slider Control class: http://pastebin.com/NcHT6RRP
Hope it helps!
Hey @Sander – thanks so much, but that’s not the part I was having trouble with – I can’t figure out where to to hook the enqueue function? What action hook are you using there?
So, from your example code you pasted, the add_action hooks to?
add_action(‘?????’, array( ‘WM4_Customize_Slider_Control’, ‘enqueue’) );
Hope that is more clear on my part!
Ah, ok.. I think I get what you mean.
You don’t use an action hook for that, but you need to use the add_control function of the wp_custom class.
This is how I use it with the custom slider:
http://pastebin.com/02VhUGqE
Hi Sander, I’ve also created my own jquery ui slider control and it works great. I am however having the same problem that you mentioned above about loading the slider AFTER the frame is loaded. Im having trouble trying to accomplish that though. I took a look at your class above – any chance of sharing the customcontrol.slider.js with us?
Kind Regards J
Sure, here’s an example (stript out all the controls and just left 1 so you’ll get the idea)
http://pastebin.com/nKb1gZzh
Hope this helps!
Hi Sander,
I followed your instruction and build my custom slider, that works pretty well.
But I have a display issue due to the default wordpress color picker, that uses the same jquery ui style.
The issue is about the vertical color slider (when color picker is open).
I’m fixing using a bit of css. But I’m not sure if it’s the best way to fix the problem.
Do you have any suggestions?
Thank you very much in advance!
Yes, that was the solution I came up with too..
Hi Sander,
Have you tried to add more than one control slider?
If I add more sliders something goes wrong: the first istance works well, the following appears broken and doesn’t work.
I can’t realize which could be the problem.
Any suggestions would be appeciated, thank you very much.
It shouldn’t be a problem. I use many sliders in my theme.
In my .js I do this:
HTML:
<input name="id; ?>" type="text" link(); ?> value="value(); ?>" />
jQuery:
$j('input[name="themex_options[main_page_width]"]').next('div.slider').slider({ *options* });
So I use the input field as selector and turn the div next to it into a slider. This way you always create an unique slider.
Hope this helps!
Thank oyu very much Sander, now seems to works perfect! 🙂
[…] via: Making a custom control for the Theme Customizer » Otto on WordPress […]
We use the customizer in our themes, it’s a great addition to WordPress. We have various individual color options implemented, and a color scheme drop down so you can select a pre-defined color scheme.
The trouble is that the two don’t work that well together (although they perform fine separately). For example, no matter what color scheme is chosen the individual color options don’t change. i.e. the default color options you set are fixed.
We would ideally like to be able to select different color schemes from the drop down, and have this update the individual color option defaults. Maybe we need to do away with the color schemes as separate CSS files and just have the colors for each color scheme in a PHP (or JS?) array instead. Then, these array values could be used to update the color picker defaults. Updating these without requiring a page reload would be the goal.
When a user updates an individual color picker option then it would be preferable to be able to reset that color. A nice solution would be to have a reset icon appear next to a color option (only if a color option had been modified) to reset it back to the default.
I am just starting to look into coding this but not sure yet which is the best approach to take. Any suggestion welcome! Also open to a collaboration to get this feature up and running (possible as a Plugin).
The overall aim here is to have a set of individual color options with a drop down above to select a predefined color scheme, which then updates the unmodified individual color options dynamically. Already modified individual color options should have a reset icon to revert back to the default color (for the current color scheme).
@David Gwyer – did you ever figure out how to do this? I have the same requirement for this project I’m working on, and trying desperately to figure it out.
It should be possible now, after my core WP commit was accepted to easily allow you to change the color picker default value: http://core.trac.wordpress.org/ticket/21206#comment:65.
I haven’t implemented any code yet in our themes yet to try this out but it shouldn’t be a problem now.
[…] Making a custom control for the customizer […]
I have successfully added the jquery-ui slider to the theme customizer. However, I can’t figure out how to actually get at the values to use in my theme. I.e., I can get the slider to show up, but that’s it. Any idea how to use the slider to set values and access those values in my theme?
Thanks.
Otto, this is all good. Just one minor point:
You referred to serialised setting storage (group[option]) as the preferred method, and yet insist on using demos in non-serialised form. Please can you use serialised settings examples if that is what you say is best practice?
I ask this because I’m going crazy trying to convert your demos into serialised form….
Actually, in the previous post in this particular series, I was talking about using the theme_mod as an alternative to serialized settings in an option. So yeah, not using a single grouped option here was sort of the point of the demo, which came from there originally..
The theme_mod functions handle the grouping and serialization and storage for you. No need to put your settings into a single array and save it somewhere.
And actually, I wouldn’t say that the serialized storage is the “preferred” method. It’s just the most common. If you’re using the customizer, I’d say that the theme_mod system is preferred, because it’s much easier and cleaner.
I’m in the process of converting all my themes over to using “Customize” but I have one issue. I can’t put enough information inside the label in case someone really doesn’t know what their doing. Which is why I would like to ask if it is possible to put a link in there that would take them to a more detailed explanation?
Hi Otto,
I am in the process of creating a WP custom theme and I will use theme customisation to give the user the posibility to change some elements in the theme. Several elements changable will be CSS elements which based on the standard implementation of theme customizer will be inserted in the page header.
My problem is that i will use an CSS framework and I wonder if it is possible, when changing the CSS values in customizer and click save and close … the changes to be written to my CSS framework stylesheet instead of header of page.
This will achieve 2 things : my page header will be clean and nice and the CSS framework stylesheet will contain at any moment the right CSS updated.
I tryed to trace and debug the Save … button from Theme Customizer but i got stuck with no good results.
Thank you
You’re overthinking it. Why do you care that your “page header will be clean and nice”? Are your users admiring the cleanliness and beauty of the HTML? Do the viewers of the website think that the layout of the code and files is important? Or are they just looking at the webpage?
The HTML is just the medium, not the goal, nor the result. Your HTML doesn’t need to be clean, but the PHP code does need to be easily manageable, for the purposes of future expansion and modification. It’s more important for the code to act in a simple and sane way than it is for the HTML to “look good”.
Given that principle, putting the custom CSS code into the header is better than having a bunch of wacky code trying to rewrite files on the server. Writing files like that is potentially insecure on some (common) hosting configurations, and if you want your code to be portable and such, then making it not do that is a good idea. It isn’t that it’s not possible, because it’s certainly doable. It’s just probably not a good idea for most cases.
Yes, static CSS is “more optimal”, but in a realistic situation, is it really worth adding a bunch of code to rewrite the CSS and deal with the file management, rather than simply, quickly, and easily outputting a single line of compressed CSS overrides to the html head? Especially for something that probably isn’t all that much in the first place? I mean, it’s not like you’re creating a few hundred lines of CSS here. Anything more than, say, 30-ish lines of CSS is probably adding too many options to begin with.
Why try and convince him otherwise, it something he wants to do and I don’t blame him. I honestly see it as the next step, but not necessarily a step that needs to be taken though, and I have been considering how I would do it too, but unlike Alex… I just haven’t gotten around to trying to implement it yet.
I’m unsure about CSS framework… haven’t mess it ever, but I think there has to be something out there to do this, and if there isn’t we should look into creating it.
It’s not that you *can’t* do it, it’s that you *shouldn’t*. Unless you do things exactly right, it will lead to vulnerabilities on specific hosting configurations.
If you’re really insane enough to want to try, read my post about the WP_Filesystem. It will tell you how to do it in ways that will maintain security, although your users might not like having to put in FTP credentials to save their settings.
That doesn’t sound like a good solution… I’m more thinking along the lines of a CSS, similar to how a page is generated with the PHP code, probably would need to cache that code too. I honestly have no idea how to do this, I just know I want to some how customize the style.css page.
You’d be better off doing something like Jetpack’s Custom CSS feature does. It saves your custom CSS as a custom post type, then includes a callback in the head to get it into the page.
Editing files in the theme is problematic for a lot of reasons. Writing files directly leads to potential security issues. Changing files in the theme leads to issues with losing those changes during upgrades. Things like that. Custom changes should be stored outside the theme itself, and injected in using other means.
I actually build a module to recompile CSS when needed, using the LESS CSS framework. After saving the settings from the Live Designer, my module will run a recompile with the new variables from the database. So the CSS is only generated when changes have been made. And I don’t write the CSS to a file, I use wp_register_style to serve up a .php file, that will output the new CSS or a 304 not modified.
Works like a charm!
This sounds a lot like what I was going to look into, any chance you have shared this code or got any hints where to look into this? I would hate to do leg work that wasn’t necessary.
I can’t share all of it, but this should get you started:
– First I enqueue the style.php with this code: http://snipt.org/vhhhj8
– The style.php files contains: http://snipt.org/vhhhi5
The LESS CSS compiler was build on the LESS CSS class, more info can be found here: http://leafo.net/lessphp/docs/
Good luck 🙂
Wow guys,
I didn’t entered yesterday to check out for replies and today i see a tone of responses.
Thank you Otto for your advices, but unfortunately i plan to modify a lot of my theme and doing so, it will create a long CSS code in my header. Therefore i tend to take the advice of Sander because it suits better my needs.
Wow again Sander … as i said above i think your approach fits me better so if you bear with me 2-3 minutes i will recap what i understood from your replies:
– As i will use bootstrap framework i need to include its CSS in the style.css
– Along with those bootstrap styles I plan to create custom theme CSS which will be in the PHP file you said and of course in the database. This rise a problem for me not knowing if i should import the cache.css file created dynamically in the style.css , or it will be inserted by the code of your first snipet. ( Enqueue style.php )
– After all this style settings, all i must do is to find a way to generate the cache.css file from database. This should be trivial work, but who knows what other problems could appear.
The only problem i see for this approach is that if someone tries to modify the CSS directly on cache.css, the changes will work until the next update from database. At that moment all direct modifications on cache.css will be replaced with database values. But that is not a problem for me really
Please tell me if i understood your approach and if not please guide me where i am wrong.
Thanks
Sure, no problem..
– I use Twitter bootstrap as my base CSS. Just enqueue it like theme.php and make sure it’s loaded first. My style.css actually only contains nothing but Theme details 🙂
– The first snippet loads style.php in the head. Then style.php displays the CSS from cache.css if it’s a new visitor or there’s no update to the CSS. When we have modified the cache.css it will display the new CSS. So there’s no need to include cache.css again.
– I generate the cache.css file whenever there are settings saved in the ‘theme designer’. After that style.php will see a new file date and will server up the updated CSS and browsers will update it in the browser cache. This way, we don’t need to load dynamic vars from the database on every pageview. It really speed up my theme!
– I give my users the option to upload their own additional CSS file. So that way there’s no need to change anything in cache.css and if they will it gets fixed on the next update 😉
And yes, this approach costs additional requests against the inline CSS way of doing it, but using caching I think it’s a fast solution and a lot cleaner way of working.
Last note: Security is indeed an important issue that you need to take care of, just like Otto said. Check out Otto’s tutorial on WP_filesystem to make sure it’s done the right way.
Hope this helps! Took me some very long nights of coding and testing to figure it out 😉
Greets, Sander
Hi Sander,
I use too twitter’s bootstrap framework and besides the obvious advantages of using bootstrap it gives you certain limitations regarding the css.
I mean the bootstrap core CSS will remain in the bootstrap.css but I also need a css for the responsive elements of the theme which i can insert into bootstrap.css or style.css or any other css except cache.css. And the last css file would be cache.css, where i put the custom features of the theme.
I tryed to understand your approach which until some point i got it, but there are some elements that i don’t get it.
In the first snippet you use the syntax : wp_register_style(“lesscss”, THEMEDIR . “/css/styles.php?gen=” . filemtime( THEMEDIR . ‘/css/cache/cache.css’ ) );
This inserts the style.php in the theme’s header. I don’t understand the presence of less here but i accept it.
The second snippet makes the magic from cache.css which is generated dynamicly from database. Does the cache generation is using somehow less framework or what role does the less plays in the whole scenario ? ( being new to less i would ask you how you install it – javascript install, php install ? )
I put the last question because we can generate cache.css without any help so i don’t understand the presence of less.
I hope you understand my puzzle here.
Thanks
Well, I think I can answer your question very quickly: I only use LESS when generating the cache.css with the custom variables in the database. BUT there’s no need to use LESS if you don’t want to. You could generate CSS just how you like it.
I think LESS is an efficient way of building and managing stylesheets once you get the hang of it. I love the mixins for example!
If you do decide to use LESS CSS, use the PHP class (check the link I gave in my second comment), then you don’t need to install LESS in anyway. I wouldn’t even know how to do it myself 🙂
Don’t want to be too pushy but since other sources like stackoverflow didn’t answered my question i will address it to you hoping you have an idea
It related with theme customization and everything we talked above but it regards the customization of menu parts. Basically the menu have 2 images on the left and right sides giving an 3d look ( pretty much like here … http://cdn.tripwiremagazine.com/wp-content/uploads/2012/06/css-multi-purpose-dropdown_thumb.jpg ).
As I want to my theme customizable i want to be able to change the color of those 2 images according to the menu background color. To complicate further the things the main content has an colored background image.
So is there any way to change those 2 elements according to clients desire ?
Thank you
I think the best approach would be using CSS(3) for the effect. That way you can change the color easily with the background color. Search Google on CSS ribbons for some ideas and examples! Hope it helps 🙂
We have quite a lot of color pickers in our latest theme to modify all the key styles so there is a fair chunk of CSS added to the header. It’s not a massive amount but perhaps enough to look into reducing it a bit more.
I haven’t implemented this idea yet but there should be a way to reduce the amount of CSS added to your header. If you have an enqueued style sheet that adds ALL the necessary styles to render your site you can then use color pickers (or other controls) to ‘override’ certain styles. Each color picker should have a default value (that matches something set in the enqueued style sheet) and then the color picker CSS only gets outputted into the header if different from the default. i.e. if it has been manually updated by the user.
So, even if you have a lot of color pickers, if (say) only 5-6 have been updated by the user then only 5-6 color styles will be outputted to the header (rather than ALL).
[…] the controls built into WordPress, how do we go about building additional controls? Otto wrote a great post on making custom controls, and this section will draw heavily on his […]
A couple of questions about the public member $type
– what purpose does it serve, and in particular…
– … is its value (“textarea” in the example) one of a set of values predefined by the API (enum-like),
– … or is it a name I am supposed to invent, that will refer to the control type being defined?
I am writing an image sequence control class. The UI will be written almost completely in JS, and a hidden field with comma-separated list of attachment IDs will be used as data interface. Should I then write:
$type = "hidden";
or
$type = "image_sequence";
?
The $type is used in several places. It’s used in the render_content() function, where it’s a pre-defined set of types. It’s used as part of the classes and some of the json handling code. And a few other things.
Basically, if you’re extending the WP_Customize_Control, then you need to use a new $type that nobody else is using, or which is obvious from the naming methodology you’re using.
Instead of extending the WP_Customize_Control, is it possible to over-ride it? For example, I’m disappointed that the default WP control for the “select” type does output with an id or class. I need some way to identify a particular select field, so I can use it in my own Javascript I’m loading in the customizer for the purpose of showing/hiding other controls based on the choice in the selection.
I meant to say that I’m disappointed that the “select” type of control DOES NOT output with any id or class. To be clear, I’d like to over-ride the default WP select control class with my own custom version of it.
Don’t override it, just extend it for your own purposes and use your own custom class instead.
[…] out Otto’s great tutorial for more info on custom controls, post any questions of suggestions in the comments […]
Hi Otto,
Thanks for sharing the knowledge. I desperately want to use the WP_Customize_Background_Image_Control() on elements other than the background so I can then use the position and repeat properties. Is it possible to do this? If so an example would be really good!
Thanks
I asked a detailed question in there:
http://wordpress.stackexchange.com/questions/82723/theme-customizer-changes-are-dissappearing-when-change-page
Basically my problem is theme customizer changes are disappearing when we change page while in live edit. Is it working as intented or am i doing something wrong? Is there a way to prevent that?
(ps to designers: if you want to see my theme customizer options for design ideas:
http://buddypress.org/support/topic/do-you-want-full-bootstrap-buddypress-theme/ )
I suggest read solution and problem on this question:
http://wordpress.stackexchange.com/questions/82723/theme-customizer-changes-are-dissappearing-when-change-page
I wasted enough time, i hope you wont waste with this 🙂
[…] had a series of articles highlighting how to use the theme customizer in your WordPress themes instead of creating an […]
I’m looking to create typography controls.
Can there be multiple controls to an actual control object?
What would be the best way to implement font controls with: font, style, size, alignment, color?
Thanks Otto!
[…] http://ottopress.com/2012/making-a-custom-control-for-the-theme-customizer/ […]
Thanks a lot, it works perfect for me.
I was curious if there is any information you know of on how to add the new WordPress 3.5 media uploader to Custom Image Upload Controllers?
I’ve found a few other references to enable the previous uploaded images tab to a Custom Image Upload Controller using Eduardo’s code here. But it doesn’t work perfectly. It would be ideal if the new WordPress Media Uploader can be cued in for the Theme Customizer. Just hoping you may have some suggestions or references. Thank you for the short tutorials. I have things somewhat working the way I need by using the get_theme_mod in a customize_css function for inserting the styles into the header of the theme.
Quick question: When I customize some part of the design, it will be gone when click on a link, to a blogpost i.e.
Is there anyway to apply the changed design settings again after a refresh/opening subpage in live preview window?
Thanks!
If that’s the case, you might have accidentally coded one of the important failsafes out with the custom code you’re experimenting with. For me, all external links in the customizer pane are bound (presumably with javascript, though I did not bother to capture or inspect the javascript event, you can do that in your browser debugger to get more information). So, I’m not sure the trouble with your installation (are you on the latest version of WordPress?) but for me, the links are bound and therefore safe, users can only click internal links to other pages within their site.
Just checked it and yes, for me when I add an event listener for `click` in Chrome, and then click an external link, jQuery handles the event, presumably just as a return false for external links.
Thanks for your reply Brian! I was talking about internal links, so for example: in the index page clicking on a blogpost title. When the live preview refreshes with the single blogpost page, my design changes are gone. So I need to save first, then click to other page. Not fun if you forget 🙂
I’ve been working on this for hours and so far I’ve found that it should be possible to click through your website in the preview and still keep the design changes. Works perfectly with 2012.
Somehow it doesn’t work for me and to get it clear I’ve stript my script to a minimum: only 1 design option left. I’ve found that customizing doesn’t work when using ‘refresh’ as transport option, only with ‘postMessage’. That might be a clue?
Here’s the script I use: http://pastebin.com/Ya7g5cjB
– Am I missing something? Doing something wrong?
– How can I debug this? To find out why the changes are gone when ‘refreshing’
I’m sure there’s a simple solution, but you know.. after hours and hours of debugging you can get lost in code 🙂
BTW:
– I’m using the latest WP version
– I have all plugins disabled
– I use Google Chrome
Hope someone can help me out, I will be very thankful 🙂
Thanks, Sander
After a good sleep and some thinking I’ve found the solution: my CSS is only generated when saving and publishing from the customizer. So there are no vars loaded and CSS generated on each page view. And that’s why Customizer can’t inject the changed values on refresh.
My solution is to generate dynamic CSS on each pageview, for Customizer only. 🙂
Thank You for the tutorial. I’m slowly learning how to leverage the WP Theme Customizer. I currently am stuck and have a question about setting an option a custom background image for a unique page element such as header or footer or sidebar. Right now, I’m using the ‘get_theme_mod’ to display an uploaded image to an element such as:
header #branding { background-image: url( '' ) repeat; }
I used ‘extends’ to add an “uploaded” tab to my Image Upload Controllers so users can select previously uploaded images, but when the “remove image” option is clicked, the header#branding {background-image: url(‘ ‘) } should default to the background-image i have set in the default styles.css file. This way, I can have several color schemes each with unique background images that load by default when activated, but can be overridden when a new image is uploaded using the Image Uploader.
I guess my problem is that the styles output from the Custom Controller still print “header#branding {background-image: url(‘ ‘); }” with a black URL in the CSS which loads in the header and overrides the default styles.css header#branding background image URL.. If I use ” $wp_customize->add_control( new WP_Customize_Background_Image_Control…” will this generate the “background-image: url (‘…’)” definition so if the Image Uploader image is removed, will it remove the “background-image: url(‘…’)” from the CSS as well in the header so the default background image shows?
Apologies if that is too confusing. Just trying to get default background images in the styles.css to load if the WP_Customize_Background_Image_Control is empty. The Theme Customizer inserts an empty “background-image: url( ); ” in the header and overriding the background-image in the style.css.
Is there a way to use “WP_Customize_Background_Image_Control” and make sure it generated the “background-image: url( ); ” definition as part of the control? I’m a bit confused if this Custom Control is default-specific to the body background image.
Thanx again! 🙂
Sorry, I didn’t realize the php tags would be removed…. the first line of code should read:
header #branding { background-image: url( ‘
‘ ) repeat; }
The get_theme_mod function can take two parameters. The first is the name of the theme-mod to get, the second can be a default value.
So, get_theme_mod(‘example’, ‘default’) will return “default” if the example setting does not exist.
AHA!! I think i found a work-around. I used an if statement in the Theme Customizer styles around the
background-image:url('
and it seems to deactivate the css definition when the image is removed from the Image Uploader…I’m not sure if using “WP_Customize_Background_Image_Control” is the proper way to do this, but i’m currently using the extend on the Custom Image Uploader class to give the options for removing uploaded images…
Hey Otto,
Thanks so much for your core contributions with the Theme Customizer – you’ve convinced me and I won’t be going back to options pages! I have a question, though: working with the `WP_Customize_Image_Control()` class, I’ve added an image control to my Theme Customizer with the API, but this image control is for uploading a background image from the user (and this image is meant to be a full-screen image) and I need to automatically generate 3 or 4 image sizes when they upload this large image. I’m going to store the image URL as a data-attribute on the body class and then programmatically (with javascript) load an image of minimum possible size to save bandwidth.
Basically, I’m wondering if you can point me in the right direction to find an action hook to grab and do the resizing on upload. Also, what would be even better, if available, would be a method to force the images uploaded via the Theme Customizer to respect `add_image_size()` if I’ve enabled custom image sizes in my theme’s functions.php. Is this possible?
I have one last little bug with the Site Description/Tagline I’m trying to figure out, and not quite sure why its happening..
In my options file I have:
//Site Tagline
$wp_customize->add_setting(
'blogdescription', array(
'default' => '',
'transport' => 'refresh',
) );
$wp_customize->add_control(
'blogdescription', array(
'label' => 'Tagline',
'section' => 'title_tagline',
'type' => 'text',
'priority' => 10,
) );
The live preview updates, and displays the input on the site, but it won’t display in the Page Title & Description in the page tab. Still says, “Just another wordpress site”. When I remove the controller from the options file, I’m not getting any reflection of the input on the front side of the site…
Is my code for the ‘blogdescription’ wrong?
The strange part is, if I remove the controller for ‘blogdescription’ I can see the input reflect when previewing inside the theme customizer, and it displays on in the Page Title bar, but it wont actually display in the page under the Site Title.
Any help would be greatly appreciated. I will send a donation soon as this Theme is “out the door…”
Never mind…. forget that I had changed my header hooks for bloginfo…. :/
Hi Otto,
Great tutorial.
I’m new to php and have a very small issue with the textarea that I just can’t find a solution for.
My clients definitely can’t add any kind of html to the text area but I need to make sure every new line in the text area renders a line break on output. Any ideas?
Cheers
Dan
haha… Sorted it out.
If anyone is interested change
to
Great little tip here Dan! Thank you for including this question and solution.
Quickly –
I’m trying to figure out “How can we achieve the functionality of hiding child options when parent option is not selected, in WordPress customizer?
More Details –
Well – There are few parent bullet points (options); each might have several child options under it.
Right now what happens is all parents and child options are visible by default when I create a new custom control.
And what I want to do is similar to what happens in default “Static Front Page” customizer setting – The child options should be visible ONLY of the selected parent option.
Video –
http://www.youtube.com/watch?v=lT_yw2b4KCM
(Video is taken from http://www.yourdomain.com/wp-admin/customize.php – In WordPress Dashboard, Under Appearance -> Themes -> Customize)
Any help would be greatly appreciated.
hi, could you help me using WP_Customize_Header_Image_Control(). I have tried several times to get custom header image in header image section of WP customizer. Really appreciate any help
What i want to do is have custom header image upload via customizer
[…] -original article from Here. […]
Tried building a theme with over 50 controls and noticed the live preview window in the customizer taking over 25 seconds to load. Removing the controls, of course, reduced the load time to a few seconds.
Anyone know a way to optimize performance in the live preview when working with a large amount of controls?
@Steve, Try storing all your controls in a single serialized option array, that way there is only one call to read from the database and that should take advantage of db caching.. so when adding settings
$wp_customize->add_setting( ‘my_theme_options[my_setting]’, …. );
Hi Otto and commenters,
Great tutorial and good comments.
Am looking for some enhancements to the Customizer.
1) Indicate which controller is ‘active’ in the preview.
For instance change the background color of the site title when the mouse/cursor is in the site title textbox. (Not possible with css only because the site is displayed in an iframe).
2) Add drag&drop functionality (sortable)
For instance change the order of various social icon controllers.
3) Show/hide controllers depending on the settings of other controllers.
For instance only show controller B when controller A is active/checked.
Are there any example codes around which could get me on my way or good tutorials that I have not found yet?
Thanks,
Niels
Have you ever come across an issue where the select boxes for these controls do not scroll? I have quite a large select which does not scroll with the mouse, only with the scroll wheel.
Seen this before anyone?
[…] There is no core customizer behavior that supports nested sections. However, you can roll your own customizer control which contains its own accordion sections and other […]
the control is displayed. but the setting is not saved or rendered.even the save button is not activated.any idea?
solved.just forgot to add the link to the control..working fine now.
I have just started fooling around with the customizer and this is code I think I can actually handle 😉 I am not a full fledged developer so I apologize if this sounds stupid but I am using the customizer to create a plugin. So far so good but I would like my plugin to be on it’s own… meaning that everything I have been adding so far is lumped together with the current themes customizer features. So I would like to take the Custom Control you created above and have that be the only thing that the user see’s when they launch my plugin in the Customizer but I don’t get how to do this. I know it can be done because I have seen several plugins do this. Can we get a tutorial like this?
We are implementing this for our pages. Things are working fine, but I’m curious how (or if it’s possible) to add specific styles to the actual edit sidebar (functions.php items) … There are a couple style changes I’d like to make in order to make it easier to understand what they’re editing (ie, bolding specific labels, making the radio buttons appear side-by-side )
Thanks
You should check out kirki http://kirki.org/
You can use the
customize_controls_enqueue_scripts
action hook to connect a function to the customizer controls section. In said function, you can use the normal wp_enqueue_style function to have it include a CSS file of your choosing. Using this, you should have enough to style the controls section however you like.Looking this up, i’ve gotten as far as writing something like this:
function style_the_customizer() {
wp_enqueue_style( 'wpse_89494_style_1', get_template_directory_uri() . ‘/extra_styles_customizer.css' );
}
add_action( 'customize_controls_enqueue_scripts', 'style_the_customizer' );
But I’m stumped at the part of connecting it to the customizer? Isn’t there another step?
What other step would you be looking for here? You’ve added the action, you’ve enqueued the CSS. When that action gets called in the customizer panel, that CSS file will get enqueued and then it will be included in the page. Now put CSS in there to style what it is that you want to style.
I’d be happy to answer your question, but I need to know what it is first. 🙂 What part are you having trouble with? Enqueueing your CSS makes your CSS get used. Simple as that as far as styling goes, I’d expect.
No worries! I just thought maybe, if there was something missing, it would be easily known for somebody with more experience. That’s why the vague question.
The above is basically a snippet I found, and I’m not sure what goes in place of the wpse_89494_style_1 part. I’m assuming that’s not what goes there? I’m not versed in the back-end of WordPress, and it’s been requested I make some edits.
That’s the handle of your stylesheet. It’s an identifier. You call it something unique to your code (with a prefix). It doesn’t actually matter what you have there, it just needs to be unique.
ahhh! got it! Ok… I’ll try implementing it in the functions and go from there. Thanks!
awesome… working fine. I guess I didn’t realize it was that simple. one quick follow-up question, if it’s not too much trouble.
The individual items don’t have any id’s just classes. I’m assuming I’ll have to just use things like nth-of-type and such, to style specific things?
No, each LI element that surrounds the controls has an id. Look at the controls using the Chrome Inspector.
For example, the blogname control:
The LI has an id of customize-control-blogname, so “#customize-control-blogname input” would target the input element directly.
ah! perfect! I didn’t catch that at first glance. Ok! That’s all I need! Thanks so much!
HI
Can we add two class in same file customizer.php ?
Next quesrion
Can we use different functions for different field to sanatize the value ?
Thanks for you help in advance
Hi!
This is a fantastic tutorial, but I would like to know if it is possible to do something with the API, and I’m not sure of where to look.
I have a control that uses a select menu to turn a sidebar on and off. However, I want to have the user decide whether they want the sidebar on the left or the right, but ONLY when they have set the sidebar to be on. I know this can be done with a simple jQuery listener, but can it be done with the Theme Customizer API? Other uses could be to customise footer text, but ONLY when a footer control is set to “on”. Any help that could be given would be most appreciated.
Can anyone help me about Custom control with wp_editor
How to textarea data of wp_editor save to options where it’s data-customize-setting-link= not setting.
Please help
[…] control classes. That’s outside the scope of this tutorial. Otto has a great tutorial on building controls that you can follow. Think of this as the next […]
thank you very much for posting this, it help us a lot 🙂 Nice article!
Thank you 🙂
Nice article but how would you put default sections like custom headers etc under new panel(s)?
I tweaked (for lack of a better word) a Child Theme for the Museum Core Theme By Chris Reynolds. Miraculously, I was able to successfully modify some Customizer settings from the parent theme. My problem is that I’m a non-professional developer doing stuff for friends and the less I have to be involved, once the site is implemented, the better. My friends tend to freak out by simple things, in particular, adding a background image. Is there a way to modify the Customizer’s “Background Image” section and provide for a drop down allowing the admin to pick from a list of pre-seleted background images? Any assistance appreciated. Thanks!