Search code examples
wordpresstwigtimber

Twig + wordpress - how to get filemtime for style.css


I'm using twig + timber in my wordpress theme. I have style.css file included in this way

<link rel="stylesheet" href="{{ site.theme.uri }}/dist/css/style.min.css" />

I want to add ?ver=xxxx to prevent file caching. My question is how to implement filemtime function? I want to make it like this

<link rel="stylesheet" href="{{ site.theme.uri }}/dist/css/style.min.css?ver=1202120210" />

Solution

  • There are a couple of ways you can handle this, and both involve writing some PHP.

    The first way, and the one I'd recommend, is to use wp_enqueue_style() instead of adding the <link> tag into your twig file.

    /**
     * Places the following tag into the page <head>, where
     *  `{ theme_url }` = the url of your theme directory
     *  `{ filemtime }` = the timestamp of the last modified date
     *                    for the stylesheet
     * <link rel="stylesheet" href="{ theme_url }/dist/css/style.min.css?ver={ filemtime }" />
     */
    function my_custom_css_styles() {
        wp_enqueue_style(
            'main-styles',
            get_template_directory_uri() . '/dist/css/style.min.css',
            array(),
            filemtime(get_template_directory() . '/dist/css/style.min.css'),
            false );
    }
    add_action( 'wp_enqueue_scripts', 'my_custom_css_styles' );
    

    You can put multiple stylesheets into the function if you need to, and you can include logic to load them conditionally based on post type, post ID, or anything that you can determine about the current page using PHP.

    If this does not work for you for some reason, the second method is to generate your version number with PHP and then add it as a new variable to your Timber context. Your line in Twig would look like this:

    <link rel="stylesheet" href="{{ site.theme.uri }}/dist/css/style.min.css?ver={{ style_css_version }}" />
    

    Then in your template file you would add the new style_css_version variable after defining the context:

    $context = Timber::get_context();
    $context['style_css_version'] = filemtime(get_template_directory() . '/dist/css/style.min.css');
    

    If you want to use this on every page on your site, not just pages with a specific template, you can add it to the global Timber context from your functions.php (more information at Timber - extend data to context (WordPress)):

    function my_custom_timber_context( $context ) {
        $context['style_css_version'] = filemtime(get_template_directory() . '/dist/css/style.min.css');
    }
    
    add_filter( 'timber_context', 'my_custom_timber_context'  );