Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/ScriptRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,13 @@ protected function addAttributes(): void

protected function addAttributesFilter($attributes)
{
// Themes and other plugins can print script tags without an id.
$id = $attributes['id'] ?? null;

foreach ($this->scripts as $script) {
if (
$script instanceof HasAttributes &&
$script->handle() . '-js' === $attributes['id']
$script->handle() . '-js' === $id
) {
return array_merge(is_array($attributes) ? $attributes : iterator_to_array($attributes), $script->attributes());
}
Expand Down
23 changes: 23 additions & 0 deletions tests/Regression/script-attributes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

require __DIR__ . '/../Support/isolated-options.php';

sa_with_isolated_options(static function () {
$registry = new SimpleAnalytics\ScriptRegistry();
$registry->push(new SimpleAnalytics\Scripts\AnalyticsScript());
$registry->register();

set_error_handler(static function ($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
});
try {
// Themes and other plugins may print script tags without an id.
$tag = wp_get_script_tag(['src' => 'https://example.test/other.js']);
} finally {
restore_error_handler();
}
sa_assert(strpos($tag, 'data-platform') === false, 'Unrelated scripts must not receive our attributes.');

$tag = wp_get_script_tag(['src' => 'https://example.test/latest.js', 'id' => 'simpleanalytics-js']);
sa_assert(strpos($tag, 'data-platform="wordpress"') !== false, 'Our script must still receive its attributes.');
});
Loading