Skip to content

Instantly share code, notes, and snippets.

@silaskoehler
Last active June 15, 2024 12:33
Show Gist options
  • Save silaskoehler/d8b5bcf24e48b549c52d401e3bf84637 to your computer and use it in GitHub Desktop.
Save silaskoehler/d8b5bcf24e48b549c52d401e3bf84637 to your computer and use it in GitHub Desktop.
<?php
/**
* Enqueue a script with asset file
*
* @param string $script_url the URL to the script file
* @param string $handle the handle for the script
* @param string $translation_domain the translation domain
* @param string $translation_path the translation path
*/
function luther_utils_enqueue_script( $script_url, $handle = "", $translation_domain = "", $translation_path = "" ) {
// get the web protokoll from the home url
$web_protokoll = str_contains( home_url(), 'https' ) ? 'https://' : 'http://';
// force the URLs to use the same protokoll as the home url
$script_file_url = str_replace( [ 'http://', 'https://' ], $web_protokoll, $script_url );
$content_url = str_replace( [ 'http://', 'https://' ], $web_protokoll, WP_CONTENT_URL );
// get script and asset file path
$script_file_path = WP_CONTENT_DIR . str_replace( $content_url, '', $script_file_url );
$asset_file_url = str_replace( '.css', '.asset.php', $script_file_path );
// check first if file exists
if ( ! file_exists( $asset_file_url ) ) {
return new WP_Error( 'asset_file', 'The asset file must exist' );
}
$asset_file = include ( $asset_file_url );
// check if is type of array $asset_file
if ( ! is_array( $asset_file ) ) {
return new WP_Error( 'asset_file', 'The asset file must return an array' );
}
if ( empty( $handle ) ) {
$relative_path = str_replace( WP_CONTENT_URL, '', $script_file_url );
$handle = str_replace( '/', '-', $relative_path );
$handle = str_replace( '.', '-', $handle );
}
wp_enqueue_script(
$handle,
$script_file_url,
$asset_file['dependencies'],
$asset_file['version'],
);
if ( ! empty( $translation_domain ) && ! empty( $translation_path ) ) {
wp_set_script_translations( $handle, $translation_domain, $translation_path );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment