Skip to content

Instantly share code, notes, and snippets.

@broskees
Last active December 7, 2021 20:03
Show Gist options
  • Save broskees/71c7b6bd724c89fdcba2f24e8f80de27 to your computer and use it in GitHub Desktop.
Save broskees/71c7b6bd724c89fdcba2f24e8f80de27 to your computer and use it in GitHub Desktop.
WordPress CSS & JS enqueue router
<?php
/**
* Routes specific js & css files to enqueue if they exist.
*
* (The idea is to use default.css & default.js for all your global styles,
* then simply include default.css & default.js into your $template.css & template.js files
* so that you can easily keep filesizes small and minimize the number of resources requested.)
*/
add_action( 'wp_enqueue_scripts', function() {
$template = get_current_template(false, false);
$css = file_exists( get_asset_file_path( "$template.js" ) ) ? "$template.css" : 'default.css';
$js = file_exists( get_asset_file_path( "$template.js" ) ) ? "$template.js" : 'default.js';
wp_enqueue_style(
sanitize_title($css),
get_asset_path($css),
false,
filemtime( get_asset_file_path( $css ) )
);
wp_enqueue_script(
sanitize_title($js),
get_asset_path($js),
['jquery'],
filemtime( get_asset_file_path( $js ) ),
true
);
});
<?php
/**
* Define current template file
*
* Create global variables with the name of the current
* theme template file being used.
*
* @param $template The full path to the current template
*/
add_filter( 'template_include', function ( $t ){
$GLOBALS['current_theme_template'] = basename($t);
$GLOBALS['current_theme_template_identifier'] = basename($t, '.php');
return $GLOBALS;
}, 1000 );
<?php
/**
* Get Current Theme Template Filename
*
* Get's the name of the current theme template file being used
*
* @global $current_theme_template Defined using define_current_template()
* @param $echo Defines whether to return or print the template filename
* @param $id Determines whether or not to include the file suffix
* @return The name of the template filename, including .php
*/
function get_current_template( $echo = false, $with_suffix = true ) {
$id = $with_suffix ? 'current_theme_template' : 'current_theme_template_identifier';
if( !isset( $GLOBALS[$id] ) ) return false;
if( $echo ) echo $GLOBALS[$id];
return $GLOBALS[$id];
}
/**
* gets the path to assets
*
* @return string
*/
function get_asset_path($path = null) {
return get_stylesheet_directory_uri() . "/assets/{$path}";
}
/**
* gets the file path to the asset
*
* @return string
*/
function get_asset_file_path($path = null) {
return get_stylesheet_directory() . "/assets/{$path}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment