Tuesday, February 19, 2013

Add settings to a theme

This will show you how to add your own controls to the "settings" area of a theme.

1)  Go into theme/lang/en/theme_yourtheme.php.  Here create the actual names and descriptions of your setting. Save these names for use later in code.Here is my example:


$string['endcolor'] = 'Menu gradient: End Color';
$string['endcolordesc'] = 'Change the ending color of the gradient for menu bar.';


2)  Go into theme/settings.php.  Here you can add a new type of setting, referencing the new names you just created. For example, I'm going to add a new color picker:


// Menu background colour setting
$name = 'theme_yourtheme/endcolor';
$title = get_string('endcolor','theme_yourtheme');
$description = get_string('endcolordesc', 'theme_yourtheme');
$default = '#ffffff';
$previewconfig = NULL;
$setting = new admin_setting_configcolourpicker($name, $title, $description, $default, $previewconfig);
$settings->add($setting);

3) Go into theme/lib.php. Here we need to add functions that will replace the current color with our new setting's color.
--- Within the  function yourtheme_process_css($css, $theme)       function, you need to add some code to check for your new setting. Here is an example:


if (!empty($theme->settings->endcolor)) {
        $endcolor = $theme->settings->endcolor;   <-- here we make a new variable to store our settings.
    } else {
        $endcolor = null;
    }
    $css = yourtheme_set_menuendcolor($css, $endcolor);

-- You'll see that we just called a function on the last step that doesn't exist yet:
yourtheme_set_menuendcolor($css, $endcolor);

-- So now we need to create it. At the bottom of the document, outside of any other function brackets, create your new function:


function yourtheme_set_menuendcolor($css, $menuendcolor)
{
    $tag = '[[setting:endcolor]]';
    $replacement = $menuendcolor;
    if (is_null($replacement)) {
        $replacement = '#333333';
    }
    $css = str_replace($tag, $replacement, $css);
    return $css;
}


4)  Last step is to change the theme/styles/core.css file and insert our new settings.
background:[[setting:endcolor]]


DONE!
Now you know how to make basic settings for your theme file.
Please remember to "clear theme caches" or put your site into "theme designer mode" to see these changes take place in real time.

No comments:

Post a Comment