Как поменять версию css

Принуждаем браузеры загружать свежие версии CSS и JS в WordPress

Современные браузеры кешируют большинство внешних аспектов сайта, они кешируют все изображения и даже таблицы стилей и файлы javascript вашего сайта. Во время редизайна сайта, когда вы будете изменять файлы HTML и CSS, и при тестировании этих изменений некоторые пользователи могу зайти на ваш сайт и просматривать страницу со старыми таблицами стилей, что, вероятно, приведет к тому, что дизайн отобразится «криво».

Просмотр новой страницы со старыми таблицами стилей непременно будет отображен некорректно.

Существуют несколько способов, которыми разработчики могут воспользоваться для того, чтобы браузеры подгружали самую свежую версию таблиц стилей и javascript, что реализуется помещением строки запроса в конец ссылки на таблицу стилей.

http://example.com/stylesheet.css?v=1

Теперь же, когда вы проделаете изменения, то нужно будет всего лишь изменить версию вашей таблицы стилей на 2.

http://example.com/stylesheet.css?v=2

Это сработает для браузера, и тот будет подгружать последнюю версию, так как увидит для себя «новую» ссылку. Однако разработчику придется каждый раз запоминать это значение при внесении изменений в CSS, и значение легко можно забыть.

Существует еще один способ — использование функции time(), которая будет добавлять текущее время в конец ссылки на таблицу стилей.

http://example.com/stylesheet.css?v=

Проблема заключается тут в том, что новая ссылка будет совершенно разной для каждой страницы, даже если сам stylesheet не изменился, и поэтому браузер будет каждый раз загружать новую версию, не смотря на то, что никаких изменений проделано не было.

Читайте также:  Изображение на кнопку python

Что же нужно сделать в таком случае? Нужно добавлять время последнего изменения в таблицу стилей, поместив его в ссылку на CSS файл с помощью функции filemtime().

Применяем технологию к WordPress

Для подключения таблицы стилей в WordPress вам нужно использовать функцию wp_enqueue_style(). Функция понимает определенный набор параметров. Четвертым параметром можно указать номер версии, который и будет добавлен к ссылке на ваш файл таблицы стилей.

add_action( 'wp_enqueue_scripts', 'add_styles' ); function add_styles() < $css_file = get_stylesheet_directory() . '/css/style.css'; wp_enqueue_style( 'css-file', get_stylesheet_directory_uri().'/css/style.css', NULL, filemtime($css_file) ); >

По всем вопросам и отзывам просьба писать в комментарии ниже.

Не забывайте, по возможности, оценивать понравившиеся записи количеством звездочек на ваше усмотрение.

Источник

Как обновить версию style.css?

Что за параметр ver ?? Как его обновить до версии, которая подгрузит актуальную версию style.css? Ну или как вообще убрать дописку этого параметра?
На сайте нет никаких плагинов кеширования.

deniscopro

Попробуйте заменить строку
Version: 3.1.0.1553430030
на
Version: 3.1.0.1553430031

Файлы кешируются в браузере. Изменение версии помогает изменить ссылку на файл и заставить браузер загрузить новую версию файла с сайта.

Tolly

В хроме: Ctrl + F5 сбросит кеш.
Версию задают, как уже выше сказали, чтобы браузер загружал новую версию css.
На версию можно не обращать внимание, это тоже самое, что и просто удалить версию, эффект тот же. Версия задается в functions.php, предположительно в строке вида:

wp_enqueue_style( 'main-style', get_stylesheet_uri(), array(), '3.1.0.1553430030', true );

удалите последние 3 параметра до:

wp_enqueue_style( 'main-style', get_stylesheet_uri());

iamd503

в functions.php задаётся этот параметр, посмотрите место, где этот файл стилей подключается, и там есть параметр использовать версию или нет

Войдите, чтобы написать ответ

Как изменить поле распродажа у аукционных товаров WooCommerce?

Источник

How to change version of .css in WordPress?

Like the title suggests, I’m not too sure how to change the version of a .css file in my theme. At the moment the .css versioning is like this:

Is there a script that I need to run — where should I be looking to make the version 4.6.2 as per above?

4 Answers 4

The fourth argument, $ver for wp_enqueue_style() allows you to set the version:

wp_enqueue_style( string $handle, string $src = false, array $deps = array(), string|bool|null $ver = false, string $media = 'all' ); 

$ver (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: false

Thanks for that — I guess what I am asking is ‘how do I do that’ — i.e. ‘how do I run that script to generate a new version’? Hope that makes sense.

Would you update your question with the code where wp_enqueue_style() is called? WordPress handles the versioning automatically based on the explanation of $ver posted in my answer, so I’m assuming $ver is set to false. If you want to change it, change the $ver argument to a new string (I wouldn’t use 4.6.2 since that convention is used by WordPress already), but technically it would work.

You can easily substitute anything there. For example $ver = time(); would make a new version every time you hit the page, and the version would be the time.

Mostly theme’s use wp_enqueue_style() function inside their functions.php file to add style sheet in the header. Here is how to find out if your theme does the same.

Open your wp-content/themes/YOUR_THEME_NAME/functions.php file, and find out the line which is adding the style sheet, Like:

wp_enqueue_style('main_style', get_stylesheet_directory_uri() . '/style.css'); 
wp_enqueue_style( 'twentysixteen-style', get_stylesheet_uri() ); 

You can search for the ID (except for -css part). if the ID is: main_style-css search for just main-style in your functions.php file, and you should probably find the line of code you were looking for.

Now that you found the code and you know that your theme adds this stylesheet by using wp_enqueue_style() in functions.php file. You need to update this code for version.

$style_ver = filemtime( get_stylesheet_directory() . '/style.css' ); wp_enqueue_style( 'main_style', get_stylesheet_directory_uri() . '/style.css', '', $style_ver ); 

As you can see, this code gets the last modified time of style.css file using filemtime() PHP function and it also converts the time to timestamp using time() PHP function just to make things clean.

If you don’t want the version to dynamically change every time you can simply do this:

wp_enqueue_style( 'main_style', get_stylesheet_directory_uri() . '/style.css', '', '1.5' ); 

Thats pretty much it. Peace!

Heads up: you should use get_stylesheet_directory() inside of filemtime() since it will return a system path.

I didn’t get much out of these answers so I thought I’d write what worked for me. I know the codex says:

$ver (string|bool|null) (Optional) String specifying stylesheet version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added. Default value: false

But it is very cryptic as to how it actually works. I could not get a version number in wp_enqueue_style to trigger a query param like ?ver=1.2.3 on my stylesheet. However setting it to true allows the stylesheet’s declared version to cache bust the stylesheet. (read on)

Within your style.css you must name your theme. This is required by WP. However other options such as version is what wp_enqueue_style’s version boolean gives reference too.

/****************************************************************** Site Name: MySite.com Author: @BenRacicot Version: 4.0 //  

Now when I change that to Version: 4.1 I get style.css?cache-bust=0.24135995238933283

Источник

How can I version the main CSS file?

How can I instruct wordpress to use a filename other than 'styles.css' for my main stylesheet - for example, styles-1.css? I'd like to do this for versioning and caching purposes.

9 Answers 9

Style.css is required for your WordPress theme. That's where WordPress gets the theme name and meta information for the Appearance >> Themes menu from. That said, you don't actually have to use style.css in your theme at all. I know of several readily available themes that don't use it, and I only use it in a handful of my custom designs.

In header.php just place the following tag in place of the regular stylesheet link:

This will load your alternative stylesheet as the page's stylesheet and completely ignore the regular style.css .

Just to clarify, you DO have to have a style.css file in your WordPress theme with the theme name in it. You DON'T have to load that file in your header.php file.

And you shouldn't put your styles in theme files directly - use wp_enqueue_style instead - it's much nicer for child themes and plugins.

This may be inappropriate, please let me know if I missed something.

The fourth argument to wp_enqueue_style() is the stylesheet's version number. In your theme's functions.php :

function my_theme_styles() < // replace "10" with your version number; increment as you push changes wp_enqueue_style('my-theme-style', get_bloginfo('template_directory') . '/style.css', false, 10); >add_action('wp_print_styles', 'my_theme_styles'); 

Requires that your header.php does a wp_head() , which of course you were doing anyway. 😉

This allows you to push long expiry headers with your CSS file, and force clients to download a new file by updating the version number. WP will append "?ver=N" to the URL of your CSS file.

Drop this in your theme's functions.php file:

function my_cool_style_versioner( $style ) < return str_replace( '/style.css', '/style-1.css', $style ); >add_filter( 'stylesheet_uri', 'my_cool_style_versioner' ); 

Presumably, I would need to call that function from somewhere . (and I assume the missing / is a mistake!)

Also, note that as you increase the version, the second argument ( '/style-1.css' ) will change, but the first one ( '/style.css' ) will always stay the same.

EAMann is correct, you don't have to use the style.css file for all your CSS.

For versioning the style sheet and other files in your theme you can add this to your functions.php file

function fileVersion($filename) < // get the absolute path to the file $pathToFile = TEMPLATEPATH.'/'.$filename; //check if the file exists if (file_exists($pathToFile)) < // return the time the file was last modified echo filemtime($pathToFile); >else < // let them know the file wasn't found echo 'FileNotFound'; >> 

And then when you make the link to your style sheet you can do this.

This way you don't have to manually update the version number, anytime the file is updated on the server the version will automatically change to that UNIX timestamp

A better way would be to version the filenames like by adding a number like

So my approach is the following:

Apache htaccess redirects

If you are using HTML5 boilerplate with apache you can find the following section in the .htaccess file:

# ------------------------------------------------------------------------------ # | Filename-based cache busting | # ------------------------------------------------------------------------------ # If you're not using a build process to manage your filename version revving, # you might want to consider enabling the following directives to route all # requests such as `/css/style.12345.css` to `/css/style.css`. # To understand why this is important and a better idea than `*.css?v231`, read: # http://stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring RewriteCond % !-f RewriteRule ^(.+)\.(\d+)\.(js|css|png|jpe?g|gif)$ $1.$3 [L] 

(You usually have to enable it first, by uncommenting the lines)

Theme functions.php

I wanted to automatically use the version of my theme for the stylesheet, so I came up with the following:

You can add the following to your themes functions.php:

function my_theme_styles() < $my_theme = wp_get_theme(); $version = str_replace('.','',$my_theme->get( 'Version' )); $stylesheet = get_bloginfo('stylesheet_directory').'/style.'.$version.'.css'; wp_enqueue_style('my-main', $stylesheet, false, null); > add_action('wp_print_styles', 'my_theme_styles'); 

Note, that I provided null as a version instead of false , so WordPress does not append its version in the querystring.

Result

This outputs a stylesheet like the following for Version 1.0.2 of your theme:

After I change my theme to Version 2.0.0 in my style.css it would output the following:

Additional notes

Take care, that if you just strip the dots of the version like I did you may get problems with theme version like 1.2.23 and 1.22.3, as they both result in a dotless version of 1223.

A better way would be to take that into account in the .htaccess file. Eg you could allow underscores between the numbers and could replace the dots with them.

This is untested, but should work:

.htaccess

# ------------------------------------------------------------------------------ # | Filename-based cache busting | # ------------------------------------------------------------------------------ RewriteCond % !-f RewriteRule ^(.+)\.([_\d]+)\.(js|css|png|jpe?g|gif)$ $1.$3 [L] 

functions.php

function my_theme_styles() < $my_theme = wp_get_theme(); $version = str_replace('.','_',$my_theme->get( 'Version' )); $stylesheet = get_bloginfo('stylesheet_directory').'/style.'.$version.'.css'; wp_enqueue_style('my-main', $stylesheet, false, null); > add_action('wp_print_styles', 'my_theme_styles'); 

Источник

Оцените статью