From 1648d8bb80b5f8f3f0fe7f041ea6dea5dc6e235f Mon Sep 17 00:00:00 2001 From: Simple Analytics Agent <343555763+simpleanalytics-agent@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:28:00 +0100 Subject: [PATCH] Ignore script tags without an id in the attributes filter Themes and other plugins can print script tags without an id, which made the wp_script_attributes filter emit an "Undefined array key" warning. Co-Authored-By: Claude Opus 5.5 --- src/ScriptRegistry.php | 5 ++++- tests/Regression/script-attributes.php | 23 +++++++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 tests/Regression/script-attributes.php diff --git a/src/ScriptRegistry.php b/src/ScriptRegistry.php index 7dfe61d..6cce314 100644 --- a/src/ScriptRegistry.php +++ b/src/ScriptRegistry.php @@ -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()); } diff --git a/tests/Regression/script-attributes.php b/tests/Regression/script-attributes.php new file mode 100644 index 0000000..570e004 --- /dev/null +++ b/tests/Regression/script-attributes.php @@ -0,0 +1,23 @@ +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.'); +});