首页 > 解决方案 > 在 WooCommerce 中强制重新加载 style.css

问题描述

我想强制为用户重新加载 style.css,因为他们的浏览器缓存可能会破坏设计。我正在尝试使用它的版本(fe style.css?ver=2)。

这是最好的方法吗?最终我可能会考虑运行这个动态,如链接所示。但现在我什至无法让它发挥作用。

我正在使用突出主题,如果我是正确的,他们有一个 enqueue.php 脚本可以加载 .css 文件。现在我已将 ?ver=2 添加到下面的代码中。但是,当我查看我的主页时,这仍然会改变输出。我已清除缓存并仔细检查是否允许使用查询字符串。但是服务器缓存和 WP-rocket 似乎允许这样做。关于如何让这个工作强制 style.css 重新加载的任何指示?

if( is_child_theme() ) {
        $nectar_theme_version = nectar_get_theme_version();
        wp_register_style( 'salient-child-style', get_stylesheet_directory_uri() . '/style.css?ver=2', '', $nectar_theme_version );
        wp_enqueue_style( 'salient-child-style' );
    }

UDPATE:我尝试将该代码更改为 /style2.css。这似乎确实更新了输出。所以似乎我的设置正确,但查询被切断了。

标签: htmlcsswordpressstylesheet

解决方案


我会使用filemtime. 即使没有显示版本,浏览器也应该正在读取新文件:

if( is_child_theme() ) {
        wp_enqueue_style( 
            'salient-child-style', 
            get_stylesheet_directory_uri() . '/style.css', 
            [], 
            filemtime( get_stylesheet_directory() . '/style.css' )
        );
    }

基本上,这将获取文件的修改时间,如果不同,版本将更新并让浏览器知道版本已更改。此外,您真的不需要单独的wp_register_style,但如果您想保留它:

if( is_child_theme() ) {
        $nectar_theme_version = nectar_get_theme_version();
        wp_register_style( 'salient-child-style', get_stylesheet_directory_uri() . '/style.css', '', filemtime( get_stylesheet_directory() . '/style.css' ) );
        wp_enqueue_style( 'salient-child-style' );
    }

推荐阅读