Skip to content

Commit 0beea1c

Browse files
committed
Add the wp_script_module_attributes filter, with a supporting test.
1 parent 83b0df6 commit 0beea1c

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

src/wp-includes/class-wp-script-modules.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<?php
2+
23
/**
34
* Script Modules API: WP_Script_Modules class.
45
*
@@ -14,6 +15,7 @@
1415
* @since 6.5.0
1516
*/
1617
class WP_Script_Modules {
18+
1719
/**
1820
* Holds the registered script modules, keyed by script module identifier.
1921
*
@@ -343,6 +345,20 @@ public function print_enqueued_script_modules() {
343345
if ( $fetchpriority !== $script_module['fetchpriority'] ) {
344346
$args['data-wp-fetchpriority'] = $script_module['fetchpriority'];
345347
}
348+
349+
/**
350+
* Filters the attributes for a script module tag.
351+
*
352+
* @since 6.9.0
353+
*
354+
* @param array $args Key-value pairs representing `<script>` tag attributes.
355+
* Only the attribute name is added to the `<script>` tag for
356+
* entries with a boolean value, and that are true.
357+
* @param string $id The script module identifier.
358+
* @param array $script_module The script module data.
359+
*/
360+
$args = apply_filters( 'wp_script_module_attributes', $args, $id, $script_module );
361+
346362
wp_print_script_tag( $args );
347363
}
348364
}

tests/phpunit/tests/script-modules/wpScriptModules.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1730,4 +1730,38 @@ public static function data_invalid_script_module_data(): array {
17301730
'string' => array( 'string' ),
17311731
);
17321732
}
1733+
1734+
/**
1735+
* Tests that the wp_script_module_attributes filter can modify script module attributes.
1736+
*
1737+
* @ticket 62525
1738+
*
1739+
* @covers WP_Script_Modules::print_enqueued_script_modules()
1740+
*/
1741+
public function test_wp_script_module_attributes_filter() {
1742+
$this->script_modules->register( 'foo', '/foo.js' );
1743+
$this->script_modules->enqueue( 'foo' );
1744+
1745+
add_filter(
1746+
'wp_script_module_attributes',
1747+
function ( $args, $id ) {
1748+
if ( 'foo' === $id ) {
1749+
$args['data-custom'] = 'test-value';
1750+
$args['crossorigin'] = 'anonymous';
1751+
}
1752+
return $args;
1753+
},
1754+
10,
1755+
2
1756+
);
1757+
1758+
$enqueued_modules = $this->get_enqueued_script_modules();
1759+
1760+
$this->assertArrayHasKey( 'foo', $enqueued_modules );
1761+
$this->assertSame( 'test-value', $enqueued_modules['foo']['data-custom'] );
1762+
1763+
// Check the full output to verify crossorigin attribute
1764+
$output = get_echo( array( $this->script_modules, 'print_enqueued_script_modules' ) );
1765+
$this->assertStringContainsString( 'crossorigin="anonymous"', $output );
1766+
}
17331767
}

0 commit comments

Comments
 (0)