In a previous article (How to add a color picker in your wp theme using frabtastic) we explained how you could add color pickers using frabtastic in a custom WordPress admin panel for a specific theme. In this article we will provide you with an example on how you could extend this even further. So, instead of copy/pasting the code and markup for each color picker why not create the markup and code just once and reuse it for all other color pickers.
Enjoy this code and if you have any questions drop us a comment below. You can download the entire code as a twentyten child theme.
At the top of your functions.php add:
//define your color pickers
$colorPickers = array(
array('ID' => 'color_1', 'label' => 'Color 1', 'default_color' => '#002c84'),
array('ID' => 'color_2', 'label' => 'Color 2', 'default_color' => '#002c84'),
array('ID' => 'color_3', 'label' => 'Color 3', 'default_color' => '#002c84'),
array('ID' => 'color_4', 'label' => 'Color 4', 'default_color' => '#002c84'),
);
The Markup:
<?php foreach($colorPickers as $colorPicker): $colorOption = get_option($colorPicker['ID']); if (empty($colorOption) || $colorOption == ''): add_option($colorPicker['ID'], $colorPicker['default_color']); endif; ?> <div> <label for="<?php echo $colorPicker['ID']; ?>"><?php _e($colorPicker['label']); ?></label> <input type="text" id="<?php echo $colorPicker['ID']; ?>" value="<?php echo get_option($colorPicker['ID']); ?>" name="<?php echo $colorPicker['ID']; ?>" /> <div id="<?php echo $colorPicker['ID']; ?>_color"></div> </div> <hr /> <?php endforeach; ?>
The jQuery:
var colorPickers = $('.color-picker');
for (e in colorPickers) {
if (colorPickers[e].id != undefined ) {
var colorPickerID = colorPickers[e].id;
$('#'+ colorPickerID + '_color').farbtastic('#' + colorPickerID);
}
}
The function to save it all in the DB:
function color_picker_option_update()
{
global $colorPickers;
foreach($colorPickers as $colorPicker) {
update_option($colorPicker['ID'], esc_html($_POST[$colorPicker['ID']]));
}
}