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.

About Devin

I am a developer based in Austin, Texas. I run a little theme shop called DevPress and help manage a WooCommerce shop with Universal Yums. Find me on twitter @devinsays.

45 Responses

  1. suitordeanima

    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? :)

  2. shawn

    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.

  3. david

    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.

  4. Lore

    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?

  5. Valentina

    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!

  6. Toby

    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. Lore

        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. Lore

        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.

      3. Lore

        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.

  7. toby

    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

  8. GT

    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?

  9. 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?

  10. elad

    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. elad

        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.

  11. Lore

    @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.

  12. 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

  13. 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!

  14. Rafael

    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?

  15. Rafael

    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?

  16. Paolo

    Hello Guys, hope someone could help me. Im kinda lost here.

    Ok Installed Option Framework and, based on the tutorial I added a color picker in the settings which is ;

    $options[] = array(
    ‘name’ => __( ‘Colorpicker’, ‘theme-textdomain’ ),
    ‘desc’ => __( ‘No color selected by default.’, ‘theme-textdomain’ ),
    ‘id’ => ‘example_header’,
    ‘std’ => ”,
    ‘type’ => ‘color’
    );

    Now I have a header with a class name of “site-header” – so I want my users to change the background color of the header with theme options. However when I change the color nothing is happening. Kindly please help me here.

    Thanks

  17. im just new to this option theme dev and i was creating a mdb theme with options to change nav and footer colors are same time , place the js vars in with correct hex color code in buttom of options as the js isnt that long after all, but i find it extremely differcult to get to colors running on my theme , any suggestions on why that would be

Leave a Reply to Devin Cancel reply