I think this can help you. I did something similar in one of the plugins I’m developing.
static function enqueue_admin_scripts( string $hook_suffix ): void {
if ( self::get_page_hook_suffix() !== $hook_suffix ) {
return;
}
$utils_path = self::get_utils_script_path();
if ( ! empty( $utils_path ) ) {
wp_enqueue_script( 'my-plugin-utils', $utils_path );
}
}
static function get_utils_script_path(): string {
$relative_path="/path/to/utils.js"; // Adjust the relative path accordingly
// Check if the file exists in the child theme
$child_theme_path = get_stylesheet_directory() . $relative_path;
if ( file_exists( $child_theme_path ) ) {
return get_stylesheet_directory_uri() . $relative_path;
}
// Check if the file exists in the parent theme
$parent_theme_path = get_template_directory() . $relative_path;
if ( file_exists( $parent_theme_path ) ) {
return get_template_directory_uri() . $relative_path;
}
// Check if the file exists in the plugin
$plugin_path = plugin_dir_path( __FILE__ ) . $relative_path;
if ( file_exists( $plugin_path ) ) {
return plugins_url( $relative_path, __FILE__ );
}
// Return an empty string if the file does not exist in any of the locations
return '';
}
static function determine_context(): ?string {
// Implement logic to determine if the context is a plugin or theme
// You can check the backtrace or look for specific functions or classes
// Return 'plugin', 'theme', or null
}