Поддержка Проблемы и решения Принудительное обновление кеша style.css

  • Всем привет

    Сталкиваюсь с проблемой.

    При каждом изменении файла style.css стили на сайте не обновляются (особенно в опере) пока не почистить кеш. Как быть?

    Нашел в интернете множество решений, там речь идёт о замене версии файла style.css. Но как быть, если в теме style.css вызывается функцией wp_head и в конце файла
    <link rel=’stylesheet’ href=’http://сайт.ru/wp-content/themes/mytheme/style.css?ver=4.7.3&#8242; type=’text/css’ media=’all’ />
    версия берётся из версии самого движка wordpress???

    Подскажите, пожалуйста, как сделать так, чтобы любые изменения файла style.css сразу были видны всем пользователям!

    Спасибо!!!

Просмотр 6 ответов — с 1 по 6 (всего 6)
  • Модератор Yuri

    (@yube)

    в теме style.css вызывается функцией wp_head

    По всей видимости, используется функция wp_enqueue_style(). Ее четвертый параметр — версия. Можно в качестве версии скормить time(), тогда версия будет меняться каждую секунду.

    Матчасть: https://developer.wordpress.org/reference/functions/wp_enqueue_style/

    Модератор Denis Yanchevskiy

    (@denisco)

    WordPress-разработчик, denisco.pro

    Привет.

    Я использую для этого функции-обертки.

    /**
     * Enqueues script with WordPress and adds version number that is a timestamp of the file modified date.
     * 
     * @param string      $handle    Name of the script.
     * @param string|bool $src       Path to the script from the template directory of WordPress. Example: '/js/myscript.js'.
     * @param array       $deps      An array of registered handles this script depends on. Default empty array.
     * @param bool        $in_footer Optional. Whether to enqueue the script before </head> or before </body>.
     *                               Default 'false'. Accepts 'false' or 'true'.
     */
    function enqueue_versioned_script( $handle, $src = false, $deps = array(), $in_footer = false ) {
    	wp_enqueue_script( $handle, get_template_directory_uri() . $src, $deps, filemtime( get_template_directory() . $src ), $in_footer );
    }
     
    /**
     * Enqueues stylesheet with WordPress and adds version number that is a timestamp of the file modified date.
     *
     * @param string      $handle Name of the stylesheet.
     * @param string|bool $src    Path to the stylesheet from the template directory of WordPress. Example: '/css/mystyle.css'.
     * @param array       $deps   An array of registered style handles this stylesheet depends on. Default empty array.
     * @param string      $media  Optional. The media for which this stylesheet has been defined.
     *                            Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print',
     *                            'screen', 'tty', or 'tv'.
     */
    function enqueue_versioned_style( $handle, $src = false, $deps = array(), $media = 'all' ) {
    	wp_enqueue_style( $handle, get_template_directory_uri() . $src, $deps = array(), filemtime( get_template_directory() . $src ), $media );
    }

    Использование:

    function themename_scripts() {
    	enqueue_versioned_style( 'themename', '/style.css' );
    	enqueue_versioned_script( 'themename', '/js/scripts.js', array( 'jquery'), true );
    }
     
    add_action( 'wp_enqueue_scripts', 'themename_scripts' );

    Версия будет меняться при каждом обновлении файла.

    Модератор Yuri

    (@yube)

    Denis Yanchevskiy, отличное решение!

    В декларации подправьте Path to the script from the root directory of WordPress. В «обертке» — template directory.

    Модератор Denis Yanchevskiy

    (@denisco)

    WordPress-разработчик, denisco.pro

    В декларации подправьте Path to the script from the root directory of WordPress. В «обертке» — template directory.

    Поправил. Благодарю.

    Я ещё добавлю, что при при использовании дочерней темы номер версий style.css подставляется из указанной в её заголовке.
    Если, конечно, нигде не определено иное.

    @denisco спасибо, реально помогло на одном упертом хостинге, где статика жестко кэшируется промежуточным прокси на месяц.

Просмотр 6 ответов — с 1 по 6 (всего 6)
  • Тема «Принудительное обновление кеша style.css» закрыта для новых ответов.