Add Stylesheet To The Starter Theme
What is the proper method for adding a stylesheet to the Timber starter theme for WordPress?
I would normally enqueue my stylesheet in functions.php. But is this the right way?
Answer
You can add your stylesheets in functions.php (the Wordpress traditional way) or use a custom function (to be added in functions.php) that allows you to add the stylesheets directly into the twig templates. This way you can enqueue a stylesheet only where it is actually used.
The Timber starter theme has a specific section for custom functions in the functions.php file.
Function to add to functions.php
:
/** This is where you can add your own functions to twig.
*
* @param string $twig get extension.
*/
$function = new Twig_SimpleFunction('enqueue_style', function ($handle, $src) {
wp_enqueue_style( $handle, get_stylesheet_directory_uri() . '/static/css/'.$src);
});
$twig->addFunction($function);
change /static/css/
to suit your needs. Now you can enqueue the styles directly into your twig templates like this:
{{ enqueue_style('global','global.css') }}
If you need to add external stylesheets you can use a slightly different function:
/** This is where you can add your own functions to twig.
*
* @param string $twig get extension.
*/
$function = new Twig_SimpleFunction('enqueue_style_ext', function ($handle, $src) {
wp_enqueue_style( $handle, $src);
});
$twig->addFunction($function);
and then enqueue like this:
{{ enqueue_style_ext('tachyons','https://cdnjs.cloudflare.com/ajax/libs/tachyons/4.11.1/tachyons.min.css') }}
The original function was posted in a timber github issue
Related Questions
- → CORS missmatch because of http
- → Building sitemap for 2 wordpress install under 1 domain
- → How to remove empty elements after class?(jQuery)
- → Get width of an element and apply to another relative to the first one?
- → How to remove caption p class from wordpress?
- → 301 Redirection from no-www to www in wordpress
- → Laravel 5 routing using prefix
- → WordPress - Header position Top, Left &Right
- → how to add rel=nofollow to some specific external links in wordpress
- → octobercms install error: database is not empty?
- → How to edit the index page of wordpress theme?
- → How to select a Post Type (Wordpress) to pass a filter in head?
- → What sort of URL structure should be used to display AMP HTML vs vanilla HTML