I store my themes settings using Settings API.
If I create a new setting using add_settings_field() is it possible to create another setting that will be based on the first one?
Why? Imagine I have three settings:
main_color
lighter_color
darker_color
User opens Theme Options page and sets main_color to #444. Now I want lighter_color and darker_color to automagically change values based on main_color value (#444) so after all it looks like this:
main_color = #444
lighter_color = #777
darker_color = #111
Of course I could make 3 different settings and let user pick all the colors, but it won’t be that user-friendly and the whole theme will look messy if he sets lighter_color to something darker than main_color. etc.
Any ideas? 🙂 Maybe using a callback?
UPDATE
Starting bounty.
In short words – I have some settings stored in Settings API and I want to store their slightly modified versions somewhere else, I need full and easy access to these modified values, and they should update every time their Settings API “parents” do.
First of all you need function to calculate lighter and darker colors.
Once you have values in hex form a fast way is:
Settings API use
update_option
to store data, and so aupdate_option_{$option}
is triggered after saving.Assuming you are saving main color to an option called ‘main_color’ I created a class that implement this steps:
update_option_{$option}
andadd_option_{$option}
and run a function that:Here the class:
Once you have this class included in theme or plugin just use it like so:
Where 1st argument is default main color 2nd is the lighter percentual and 3rd is darker percentual.
First argument accept hex colors in both 3 and 6 digits form and with or without ‘#’.
Bonus functionality is that this code create the default option for all 3 colors based of 1st argument when the user has not setted nothing yet.
Convert function from rgb to hsl and reverse are taken from here and just a little bit adapted.
Edit
On stackoverflow I found an function that convert lighter and darker hex colors direcly. I think is a bit slower than my solution (maybe), but is much easier to implement.
Code is here https://stackoverflow.com/questions/3512311/how-to-generate-lighter-darker-color-with-php#11951022 If you want, edit my class to generate lighter and darker colors using that function.
Only note that stackoverflow function accept ligh increase/decrease in a form from -255 to 255 (negative = darker / positive = lighter) my class accepts percentual values that maybe are more intuitive.