Skip to main content
Login Join
Snippet · PHP

Enqueue Scripts and styles with timestamp versioning in WordPress.

Shared by Ravi Makwana · June 2, 2026 · @wp_enqueue_scripts

17 views
3 upvotes
Back to Snippets

This code enqueues CSS and JavaScript files in WordPress while automatically using the file’s last modified timestamp (filemtime()) as the version number. Every time you update main.css or main.js, the timestamp changes, causing WordPress to generate a new URL version (e.g., main.css?ver=1748851234), which forces browsers to load the latest file instead of using a cached copy. The main benefits are automatic cache busting without manually updating version numbers, ensuring users always see your latest changes, reducing troubleshooting caused by browser caching, improving development workflow, and helping prevent issues where outdated CSS or JavaScript files continue to be served after deployment.

<?php 
/* Use this when parent theme used */

wp_register_style('main-css', untrailingslashit( get_template_directory_uri() ).'css/main.css', ['bootstrap'], filemtime(untrailingslashit( get_template_directory() ).'css/main.css'), 'all');
wp_enqueue_style('main-css');

wp_register_script('main', untrailingslashit( get_template_directory_uri() ).'js/main.js', ['jquery', 'slick-slider'], filemtime(untrailingslashit( get_template_directory() ).'js/main.js'), true);
wp_enqueue_script('main');



/* Use this when child theme used */

wp_register_style('main-css', untrailingslashit( get_stylesheet_directory_uri() ).'css/main.css', ['bootstrap'], filemtime(untrailingslashit( get_stylesheet_directory() ).'css/main.css'), 'all');
wp_enqueue_style('main-css');

wp_register_script('main', untrailingslashit( get_stylesheet_directory_uri() ).'js/main.js', ['jquery', 'slick-slider'], filemtime(untrailingslashit( get_stylesheet_directory() ).'js/main.js'), true);
wp_enqueue_script('main');


/* 
<h5>More Information</h5>
The returning path does not contain a trailing slash.
An example output of get_stylesheet_directory() is /home/user/public_html/wp-content/themes/my_theme
In the event a child theme is being used, that is the directory that will be returned, not the parent theme directory (use get_template_directory() instead if you want the parent directory).
To retrieve the URI of the stylesheet directory use get_stylesheet_directory_uri()
To retrieve the path of a parent theme, use get_template_directory()
*/