Last active
April 17, 2026 22:12
-
-
Save widoz/3d7b56c2a9687e1c2b58f27ec9162323 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /** | |
| * Add an action that will be executed when a specific module is imported via importmap. | |
| * | |
| * WordPress does not allow modules to depend on scripts. As such, we investigate the `importmap` | |
| * for the presence of a module and execute an action when it is found. | |
| * The action shall take care of registering / enqueueing the appropriate scripts. | |
| */ | |
| function add_action_on_module_import(string $moduleName, callable $action): void | |
| { | |
| add_conditional_filter( | |
| 'wp_inline_script_attributes', | |
| static fn (array $attributes, string $data) => array_key_exists('type', $attributes) | |
| && $attributes['type'] === 'importmap' | |
| && str_contains($data, $moduleName), | |
| static function (array $attributes) use ($action): array { | |
| $action(); | |
| return $attributes; | |
| } | |
| ); | |
| } | |
| /** | |
| * Add a filter that will be executed only if a condition is met. | |
| * The condition is a callable that receives the same arguments as the filter. | |
| */ | |
| function add_conditional_filter(string $name, callable $condition, callable $callback): void | |
| { | |
| $filterCallback = static function (mixed ...$args) use ( | |
| $name, | |
| &$filterCallback, | |
| $condition, | |
| $callback, | |
| ): mixed { | |
| if (!$condition(...$args)) { | |
| return $args[0] ?? null; | |
| } | |
| remove_filter($name, $filterCallback); | |
| return $callback(...$args); | |
| }; | |
| add_filter($name, $filterCallback, 10, PHP_INT_MAX); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment