Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wordpress custom enqueue scripts and styles
/**
* @custom:mytheme
* Enqueue scripts and styles. Different paths depending on `SCRIPT_DEBUG` value,
* first resource found is used: this allows using file names including hashes
* (webpack style) to avoid chaching, i.e. `main.[hash].css`
* https://codex.wordpress.org/Debugging_in_WordPress
*/
function mytheme_scripts() {
$assetsDir = (SCRIPT_DEBUG == true ? '/dev' : '/dist');
$dir = new DirectoryIterator(get_stylesheet_directory() . $assetsDir);
foreach ($dir as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'css') {
wp_enqueue_style(
'mytheme-style',
get_template_directory_uri() . $assetsDir . '/' . $file,
array(),
null,
'screen' );
} elseif (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
wp_enqueue_script(
'mytheme-script',
get_template_directory_uri() . $assetsDir .'/' . $file,
array(),
null,
true );
}
}
}
add_action( 'wp_enqueue_scripts', 'mytheme_scripts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.