Skip to content

Commit d42673e

Browse files
authored
Merge pull request #3 from LinkForty/fix/pixel-tag-attributes
fix: put the pixel's data attributes on its own script tag
2 parents d3a1c4e + 4a17340 commit d42673e

1 file changed

Lines changed: 21 additions & 2 deletions

File tree

‎includes/class-linkforty-pixel.php‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,11 @@ public static function attributes() {
132132
/**
133133
* Adds the configuration attributes to the enqueued script tag.
134134
*
135-
* @param string $tag The `<script>` HTML.
135+
* `$tag` also holds the inline bootstrap printed before the pixel, so the
136+
* attributes must go on the pixel's own `<script src>` tag: the pixel reads
137+
* them from `document.currentScript` and sends nothing without a site key.
138+
*
139+
* @param string $tag The `<script>` HTML, inline scripts included.
136140
* @param string $handle Script handle.
137141
* @return string
138142
*/
@@ -149,6 +153,21 @@ public static function add_attributes( $tag, $handle ) {
149153
$extra .= ' ' . $name . '="' . esc_attr( (string) $value ) . '"';
150154
}
151155

152-
return preg_replace( '/<script\b/', '<script' . $extra, $tag, 1 );
156+
// WordPress gives the pixel tag the id `{handle}-js`, quoted with ' up to
157+
// 6.3 and " from 6.4. Fall back to the first tag with a src if an
158+
// optimization plugin has rewritten the id.
159+
$patterns = array(
160+
'/<script\b(?=[^>]*\sid=([\'"])' . preg_quote( self::HANDLE . '-js', '/' ) . '\1)/',
161+
'/<script\b(?=[^>]*\ssrc=)/',
162+
);
163+
foreach ( $patterns as $pattern ) {
164+
$count = 0;
165+
$tagged = preg_replace( $pattern, '<script' . $extra, $tag, 1, $count );
166+
if ( $count > 0 ) {
167+
return $tagged;
168+
}
169+
}
170+
171+
return $tag;
153172
}
154173
}

0 commit comments

Comments
 (0)