Jump to content

Module to Add version to css


Recommended Posts

Posted (edited)

Hi, So im attempting to add a version to css and js files by using a module so that any updates to the css files will be available to end users without them having to force refresh as not all end users know the process.

Here is the code I currently have but its not working.  No errors are thrown up.

 

<?php
/**
 * Copyright since 2025
 *
 * @author    Ray
 * @copyright Since 2025
 * @license   FREE
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

class AutoVersionAssets extends Module 
{
  public function __construct() {
    $this->name = 'autoversionassets';
    $this->tab = 'Blocks';
    $this->version = '1.0.0';
    $this->author = 'Ray';
    $this->need_instance = 0;
    $this->ps_versions_compliancy = ['min' => '8.0.0', 'max' => _PS_VERSION_];
    $this->bootstrap = false;

    parent::__construct();

    $this->displayName = $this->l('Auto Version Assets');
    $this->description = $this->l('Appends ?v=filemtime to all CSS and JS assets for cache busting.');
  }

  public function install() {
    return parent::install() &&
      $this->registerHook('actionFrontControllerSetMedia');
  }

  public function uninstall() {
    return parent::uninstall();
  }

  public function hookActionFrontControllerSetMedia( $params ) {
    $controller = $params['controller'];

  // Process CSS files
  $newCss = [];
    foreach ( $controller->css_files as $uri => $media ) {
      if ( strpos( $uri, 'http' ) === false && file_exists( _PS_ROOT_DIR_ . '/' . ltrim( $uri, '/' ) ) ) {
        $mtime = filemtime(_PS_ROOT_DIR_ . '/' . ltrim( $uri, '/'));
        $newCss[$uri . '?v=' . $mtime] = $media;
      } else {
        $newCss[$uri] = $media;
      }
    }
  $controller->css_files = $newCss;

  // Process JS files
  $newJs = [];
    foreach ( $controller->js_files as $uri => $value ) {
      if ( strpos( $uri, 'http' ) === false && file_exists(_PS_ROOT_DIR_ . '/' . ltrim( $uri, '/')))  {
        $mtime = filemtime(_PS_ROOT_DIR_ . '/' . ltrim( $uri, '/'));
        $newJs[$uri . '?v=' . $mtime] = $value;
      } else {
        $newJs[$uri] = $value;
      }
    }
    $controller->js_files = $newJs;
  }
}

Would anybody have any idea why it's not working. (The site is fine, just that the ?v=234234235 is not added)

 

Edited by Ray UK (see edit history)
Link to comment
Share on other sites

Please open file: classes\controller\FrontController.php

Lines 1004:         Hook::exec('actionFrontControllerSetMedia', []);

So $params['controller'] does NOT exist.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...