I'm using MediaWiki and looking to have a different Google Analytics tag load for each wiki dependent on the database name. I'm struggling with how to do this, however, given the GA tag uses JavaScript and the array/variable I'm using is in PHP.
This is what I have thus far (the correct key => value will already be chosen by the script earlier based on the database name, so I don't have to worry about that):
$wgAnalyticsCode => [
'wiki1' => '(code 1)',
'wiki2' => '(code 2)',
'wiki3' => '(code 3)'
]
and then I have the hook that runs before the page loads and adds the tag (which is a mix of PHP/JavaScript:
$wgHooks['BeforePageDisplay'][] = function( OutputPage &$out, Skin &$skin ) {
$code = <<<HTML
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=CODEHERE"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'CODEHERE');
</script>
HTML;
$out->addHeadItem( 'gtag-insert', $code );
return true;
};
I'm not entirely sure how to get the tag from the PHP array into the JavaScript? Usually, if it was just JavaScript, I would replace "CODEHERE" with $wgAnalyticsCode, but obviously it isn't that easy given that the variable is PHP and the code is JavaScript.
Any advice would be appreciated?
you can use the use word to pass your array to the anonymous function
Example
$wgHooks['BeforePageDisplay'][] = function (OutputPage &$out, Skin &$skin) use ($wgAnalyticsCode) {
after that you can use your array inside the function body
i hope it's helpful