Example Options

Color Palettes with the Options Framework

I recently collaborated on a project with Brian Casel, another WordPress developer, who wanted options for selecting preset color palettes in the Options Framework.

The idea is that a user could choose a color palette (light,dark,vibrant) from a select box or image radio button- and all the color pickers would fill with those presets. The user could then override any of those preset colors if they choose.

View on Screenr: http://www.screenr.com/7sys

Load the Javascript

In order to have an option like this you actually don’t have to hack the Options Framework plugin at all, you just need to hook in a little javascript for the options page to use.

If you want to display the code inline, you can use this hook:

add_action('optionsframework_custom_scripts', 'optionsframework_custom_scripts');

function optionsframework_custom_scripts() { ?>

<script type="text/javascript">
jQuery(document).ready(function() {
	// Javascript goes here
});
</script>
 
<?php
}

If you have a lot of scripts, it might be better to put them all in a single javascript file and enqueue that:

if ( is_admin() ) {
	// Load additional css and js for image uploads on the Options Framework page
	$of_page= 'appearance_page_options-framework';
	add_action( "admin_print_scripts-$of_page", 'optionsframework_custom_js', 0 );	
}

function optionsframework_custom_js () {
     wp_register_script( 'optionsframework_custom_js', get_bloginfo('template_directory') .'/js/optionsframework_custom.js', array( 'jquery') );
     wp_enqueue_script( 'optionsframework_custom_js' );
}

If you are using theme version rather than the plugin version, you can just add the new javascript to options-custom.js.

The Options

Let’s keep it simple. We’ll create a new option called “Color Palettes”, which will be in a drop down select box. Then we’ll have two color pickers called “Primary Color”, “Secondary Color”:

$base_color_scheme_array = array("dark" => "Dark","light" => "Light","vibrant" => "Vibrant");
											
$options[] = array(
	"name" => "Design",
	"type" => "heading");
				
$options[] = array(
	"name" => "Base Color Scheme",
	"desc" => "Choose a base color scheme.",
	"id" => "base_color_scheme",
	"std" => "fresh",
	"type" => "select",
	"class" => "mini", //mini, tiny, small
	"options" => $base_color_scheme_array);
					
	$options[] = array( "name" => "Primary Color",
	"desc" => "The primary color for the site.",
	"id" => "primary_color",
	"std" => "#000000",
	"type" => "color" );
					
					
$options[] = array(
	"name" => "Secondary Color",
	"desc" => "The secondary color for the site.",
	"id" => "secondary_color",
	"std" => "#555555",
	"type" => "color");

Javascript

This javascript code will be triggered when someone changes the value of the select box base_color_scheme. It will go through and update our two color pickers with the new color.

jQuery(document).ready(function($) {
	// Color Scheme Options - These array names should match
	// the values in base_color_scheme of options.php
	// Dark Color Options
	var dark = new Array();
	dark['primary_color']='#e4ff31';
	dark['secondary_color']='#e4ff31';
	// Light Color Options
	var light = new Array();
	light['primary_color']='#6cff00';
	light['secondary_color']='#6cff00';
	// Vibrant Color Options
	var vibrant = new Array();
	vibrant['primary_color']='#065667';
	vibrant['secondary_color']='#065667';
	// When the select box #base_color_scheme changes
	// it checks which value was selected and calls of_update_color
	$('#base_color_scheme').change(function() {
	    colorscheme = $(this).val();
	    if (colorscheme == 'dark') { colorscheme = dark; }
	    if (colorscheme == 'light') { colorscheme = light; }
	    if (colorscheme == 'vibrant') { colorscheme = vibrant; }
	    for (id in colorscheme) {
	        of_update_color(id,colorscheme[id]);
	    }
	});
	// This does the heavy lifting of updating all the colorpickers and text
        function of_update_color(id,hex) {
             $('#' + id).wpColorPicker('color',hex);
        }
});

That’s It

For more information about the Options Framework:

Restaurant Engine

If you’re interested in the work Brian Casel is doing on this, check out restaurantengine.com.

Published by

Devin

I'm a WordPress developer based in Austin, Texas. Follow my projects on GitHub, or more general WordPress ramblings as @devinsays on twitter.

43 thoughts on “Color Palettes with the Options Framework”

  1. Great tutorial! I’ve been looking for an option like this for quite some time. I’m a little confused on which files I should specifically be adding this code to — any pointers for somebody new to this framework? :)

    1. It should be added to your theme. I’d suggest functions.php or options.php. There’s already some sample javascript using the hook in functions.php of the “Options Check” theme.

  2. + I can’t figure out why, but the colors are not updating from color scheme change. Any plans to implement this in a theme or demo?

    1. I just cut and pasted everything to double check that it worked.

      The two things I noticed is that you need to make sure you:

      a) Use get_bloginfo(‘stylesheet_directory’) if you’re loading the js file in a child theme versus a base theme.

      b) Load the js on document ready (updated the code to include it)

      If it’s not working I’d check to see if you have a js error. Most likely the file wasn’t loaded, or there is a typo in the js.

  3. Great little addition to the options framework, I love it.

    I went over to the happytables site and noticed that it has been taken to a whole new level where the admin can make the color palette changes on the front end of the website.

    Do you have any plans on sharing how to do this?
    *I love how you are able to change both the background color and image with transparency, that is seriously cool.

    huge +1 on a tutorial on how to do this on the front end.

    1. This color palette (as shown in my video) was implemented on the themes offered at my site, RestaurantEngine, not happytables.

      Easy to confuse the two, since they’re pretty similar services… though we do have different approaches design and functionality :) You’ll have to ask Noel Tock about his work on that site.

  4. watching the video, I noticed that when he selected a custom color that the ‘base color scheme’ value did not change in the select box.

    When a user modifies a custom color scheme, should not the select box switch to one like ‘custom’ or something?

    *don’t want to give the user the impression that he changes a color, and that changes the default value of the base color scheme selected.

    1. Yeah, you could have it do that if you wanted. You’d need to listen for any change event on the color pickers, and the update the select box if something new was selected.

  5. Once you have some swatches, how could you load those when the page first loads? When the admin returns? I only know how to retrieve the color values from database using php, and I don’t see any clear way to get them displayed, since adding at top of options.php made it break in IE. I simply put my new colors into text inputs and changed the background with jQuery, but they’re not visible after you save. Advice?

  6. Hello and thank you so much for your precious work. I’m learning a lot and enjoying it very much. In the second block code (the one that lets you enqueuing the script), at line 7, you may want to correct
    wp_register_script( 'optionsframework_custom_js', get_bloginfo('template_directory') .'js/optionsframework_custom.js', array( 'jquery') );
    with
    wp_register_script( 'optionsframework_custom_js', get_bloginfo('template_directory') .'/js/optionsframework_custom.js', array( 'jquery') );
    a slash is missing.

    Ciao!

  7. The options framework is great and makes things much easier for theme settings, so thanks.

    But I’m wondering if you have changed from the WP color picker to the Stefan Petre one since making this post and not updated details here? I’m getting an error saying “wpColorPicker” is not a function. Testing, it seems ColorPickerSetColor is a function but calling it, while not generating an error, is still NOT setting the the input value or the picker color.

    In this post you are calling the function on the input field but in options-custom.js you are installing the picker on the picker DIV with $(‘.colorSelector’).

    So I have tried calling ColorPickerSetColor() from the div and from the input but neither does anything. The documentation for the picker at http://www.eyecon.ro/colorpicker/ is minimal but does suggest the call is made on the input rather than the DIV.

    I have spent a couple of hours going round in circles here and had hoped to post the solution to the problem but am stumped and have run out of time today. Any pointers greatly appreciated.

    1. Hi Toby. I had made just one update, “iris” to “wpColorPicker”- as recommended by Matt Weibe as the proper way to set the colorpicker. However, I tested this and realized you’re right. wpColorPicker is not correctly updating the field. I changed this back in the post and will dig into the issue deeper.

      The other colorpicker script you saw in the Options Framework Theme is no longer used. I just removed the file so as not to confuse anyone else.

      I’ll send you an e-mail and update the post when I figured out the issue.

    2. Okay, figured it out. The “iris” notation is slightly different than the wpColorPicker wrapper.

      To update a color, use: jQuery(id).wpColorPicker(‘color’,hex);

      The post has been updated, and I’ll release an update to the Options Kit soon.

      1. It seems like the Iris colorpicker updates the text in the input, but not the actual value. So, I was trying to do a function on value change of the colorpicker, but the value doesn’t change, so what would be a good way to do a function when the chosen color changes? Thanks. :)

      2. I believe you’d want to use the .change handler: http://api.jquery.com/change/

        I also find it’s helpful to look in WordPress core for these types of things. For the header functionality, the header preview changes color when you select a new color in the colorpicker. You could see how it’s done there.

      3. Have you got a working example? I mean I can see it works in his example page to change the headline, but I can’t see how. Jquery says that .change() relies upon an updated value. I wrote the author mattwiebe, because the input value never changes. The text changes but the value doesn’t, even in his page. You can see it staying the same in Firebug.

        Nothing that I do, no variation that I try, are working to call a function on color change. So I thought maybe that’s why.

      4. Nevermind, it’s working. It was the caching, because I changed nothing & now it works. Plus, using an alert box instead of console.log causes UI bugs.

        $(‘#swatch’).wpColorPicker({
        hide: false,
        change: function(event, ui) {
        var vl = $(this).val();
        console.log (vl);
        }
        });

        Although the inspectors (like Firebug) do not show the input value changing, it is logged in the console in Chrome, if you use a console.log.

  8. Hi Devin,

    Thanks for the response and corrections. I must have downloaded the framework just before you released 1.4 so the code I had was still using the old color picker. I had assumed it was a problem of the code being newer than the details in the post but it was actually the other way around. It all works as advertised now. :o)

    On a slightly tangential note, I think the multi-value options like typeography and backgrounds are a great idea, and it would be even better if developers could create their own groups like this. To allow this I have added a hook to the end of the type switch statement in optionsframework_fields() which reads:


    default:
    $output = apply_filters('optionsframework_custom_fields', $output, $value, $option_name);
    break;

    I had to add this in again after updating the library version, but perhaps this could be rolled in as a permanent feature as I’m sure others would like to be able to make their own groups of fields.

    ~Toby

  9. Thank you for making this, it made my life a lot easier.

    The color palettes worked very well on the theme options page. But when I tried putting it in the theme customizer, the colors did not change anymore. I had to put the Color Palettes option in the theme page. I was hoping that I could put everything in the customizer. Is there a way to do that?

    1. That would requiring writing additional javascript for the customizer. Definitely possible. If I have time I’ll write it out and post an example.

  10. This is a really great and educational post.

    I like the idea of having Preset Color Schemes to work from. The only thing that I’d like to do on top of this existing code is to be able to “Save” a color palette and have a dropdown selection to choose from saved palettes – like saving a group of settings.

    Do you think that is possible?

    Any advice on how this might be achieved?

    1. It is possible, but you’d really need to hack at it some. You’d need to save those sets somewhere in the database, and rewire the option to then pull those sets.

  11. Hi, Im about a minute from buying the Options Framework Theme, I love this plugin.
    I just have one problem, The color picker let the user choose color and create a ouput of the HEX color (like: #000), What I basiclly need is a picker with an alpha option in it, It also means that the output will be RGBA (like: rgba(255, 0, 0, 0.6), Is it possible?

    Please see an example for one of the RGBA picker on (under ‘Show Alpha’):
    http://bgrins.github.io/spectrum/

    Tx

      1. Hi, got ya. Thanks for reply.
        I don’t really know to work with JS or PHP and wonder if possible with a minor changes on the plugin existing files to switch the output of the default color picker from HEX to RGB? or it too complicated then that?
        Forget about the RGBA for now..

        Thanks again.

  12. @elad: If you only want to adjust alpha, you may solve it with CSS. See method at CSS-Tricks. Place your color as a background into :before or :after element.

    When Automattic (author of the color picker) posts documentation for color.js, then you may see more solutions. I wasn’t able to solve it for this colorpicker.

  13. Hello Devin,
    I am using your OptionsFramework Theme and I have one problem.
    This Post shows how to change a color palette with a select box. But how can I cange the palette with the “images” type?

    $(#radioButton).change(…) does not work in this case…

    I hope you understand me, best regards,
    Jens Wagner

  14. Hi, very nice tutorial!!! help me a lot, works perfectly!! thx!!

    but… i wanted use the same color picker that you use on your video (Eyecon Color Picker), i’m using SMOF on my theme, you know how to change default color picker to eyecon color picker? I asked on stackoverflow, if you know, please help me! thanks again!

  15. Hi again, I’m trying to make a link that when you click, it will set some options, but it is not working, look at the code:

    I’m using this code on ‘desc’ on options framework (simple link to call function to reset):

    [Reset BG Options]
    [Reset Header Options]

    And i use this code on smof.js

    // Options to reset
    var default_options = new Array();
    default_bgoptions['bgcolor1']='#745C97';
    default_bgoptions['bgcolor2']='#4D7788';
    default_bgoptions['bgcolor3']='#7D884D';

    // Reset Some Options
    $('#reset_someoptions').click(function() {
    colorscheme = default_options;
    for (id in default_options) {
    of_update_color(id,colorscheme[id]);
    }
    });

    But clicking on the link nothing happens, I have no knowledge in jquery, is difficult to get a solution, could you help me?

  16. Hi again, I’m trying to make a link that when you click, it will set some options, but it is not working, look at the code:

    I’m using this code on ‘desc’ on options framework (simple link to call function to reset):

    <a id='reset_someoptions'>[Reset BG Options]</a>
    <a id='reset_header_options'>[Reset Header Options]</a> <!-- I need to create some of these ​​to reset different values.... -->

    And i use this code on smof.js

    // Options to reset
    var default_options = new Array();
    default_bgoptions['bgcolor1']='#745C97';
    default_bgoptions['bgcolor2']='#4D7788';
    default_bgoptions['bgcolor3']='#7D884D';

    // Reset Some Options
    $('#reset_someoptions').click(function() {
    colorscheme = default_options;
    for (id in default_options) {
    of_update_color(id,colorscheme[id]);
    }
    });

    But clicking on the link nothing happens, I have no knowledge in jquery, is difficult to get a solution, could you help me?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>