Ad

Add Stylesheet To The Starter Theme

- 1 answer

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?

Ad

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

Ad
source: stackoverflow.com
Ad