Sunday, February 16, 2014

Define a new font-face using $CFG->wwwroot

It's been several times now where I defined a new font-face type with my CSS file using an absolute url path to my website. And of course, that doesn't work if I want to port my code to another server. Or even put it on my local machine.

The best way to do this is to point my css to use the $CFG->wwwroot location when including my font files. This way, you only have to modify the config.php (one file, instead of many) to change your site url.

The way to do this is:

1)  Inside of your own theme, you should have a lib.php file. In my case, this is the file structure:  theme/mytheme/lib.php

2)  I used this forum post as inspiration, but I'll also give a quick recap down below: https://moodle.org/mod/forum/discuss.php?d=220495

3)  Inside of lib.php, create a new function:
<?php

function mytheme_process_css($css, $theme) {
    $css = mytheme_set_fontwww($css);
    return $css;
}

function mytheme_set_fontwww($css) {
    global $CFG;
    
    $tag = 'setting:fontwww';
    $css = str_replace($tag, $CFG->wwwroot . '/theme/mytheme/fonts/', $css);
    return $css;
}
?>

That part that is highlighted in yellow above, make sure that it is the location of where your font files are located. (So an extra step would be making sure you put your font files on the server to begin with :)

Next, you need to modify your css file. For myself, I defined my new font inside of theme/mytheme/style/core.css.

@font-face
{
    font-family: ArchitectsDaughter;
    src: url('setting:fontwwwArchitectsDaughter.eot'); /* IE8-9 */
    src: url('setting:fontwwwArchitectsDaughter.eot?#iefix') format('embedded-opentype'),  
         url('setting:fontwwwArchitectsDaughter.ttf') format('truetype');

}

Notice that the parts I highlighted above are the same text as the "$tag" variable I assigned in the previous functions. Also, my code has multiple font files to suit both Internet Explorer and other browsers.

Make sure to refresh the theme caches on your server and/or computer. After that, you should see your new font appear.

No comments:

Post a Comment