Skip to content

Instantly share code, notes, and snippets.

@davidfq
Created May 8, 2019 13:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfq/9bd22d992a3dfb00bec15d92b97a903b to your computer and use it in GitHub Desktop.
Save davidfq/9bd22d992a3dfb00bec15d92b97a903b to your computer and use it in GitHub Desktop.
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