wp_enqueue_script() with unknown path and maybe symlink
-
I’m developing a plugin that may also be used as a library in themes or plugins.
I need to enqueue a custom script, but I cannot know the absolute path to the script, as the final location of the library may vary. I don’t want the other developers to have to manually define a constant with the path to the library/script either, as that’s extra work for them and I want the library to be as minimalistic as possible
I also want to consider that this plugin/library might be symlinked, which means that I may not be able to know if it’s located in the plugins directory or the themes directory.
This is where it becomes the trickiest, because PHP’s magic constants __FILE__ and __DIR__ resolve the symlinks and I’m unable to figure out where the library is being used.
This is what I currently have, but is there any better way to do this?
static function enqueue_admin_scripts( string $hook_suffix ): void { if ( self::get_page_hook_suffix() !== $hook_suffix ) { return; } if ( str_contains( __DIR__, ABSPATH ) ) { // Enqueue script taking into account that MY_PLUGIN may be either a plugin or a library used in another plugin or theme. $utils_path = trailingslashit( str_replace( ABSPATH, '/', __DIR__ ) ) . 'utils.js'; } else { // The plugin has been symlinked and the previous enqueue method won't resolve. $utils_path = plugin_dir_url( __FILE__ ) . 'utils.js'; // When using the MY_PLUGIN as a library, MY_PLUGIN_DIR must be defined in your plugin or theme using the right path. if ( MY_PLUGIN_DIR !== dirname( __DIR__, 2 ) ) { $utils_path = trailingslashit( MY_PLUGIN_DIR ) . 'includes/Settings/utils.js'; } else { if ( ! defined( 'MY_PLUGIN_DISABLE_LOG' ) || ! MY_PLUGIN_DISABLE_LOG ) { error_log( "WARNING: MY_PLUGIN has been symlinked. The script utils.js might not be loading correctly. If it is not loading correctly and you are using MY_PLUGIN in your theme or plugin, please define the constant MY_PLUGIN_DIR with the correct path to MY_PLUGIN. To disable this warning, use define( 'MY_PLUGIN_DISABLE_LOG', true ) in your functions.php or your plugin main file." ); } } } wp_enqueue_script( 'my-plugin-utils', $utils_path ); }
I would like to be able to simplify this as well as to offer a bulletproof solution without requiring a constant to be defined.
- The topic ‘wp_enqueue_script() with unknown path and maybe symlink’ is closed to new replies.