Code Bytes
Stop New Relic injecting browser scripts into WordPress AMP pages
Disable automatic browser instrumentation only on AMP responses without editing a plugin or switching off server-side monitoring.
An AMP response can fail validation when another tool adds an ordinary script tag. If New Relic's PHP agent is responsible, disable its automatic browser injection for that response—not monitoring across the entire site.
Put the exception in your own code
For a WordPress site using the official AMP plugin, place this in a small site-specific plugin or an existing must-use plugin. Do not edit the AMP plugin's files: its next update would overwrite the change.
<?php
add_action('wp', static function (): void {
if (!function_exists('amp_is_request') || !amp_is_request()) {
return;
}
if (function_exists('newrelic_disable_autorum')) {
newrelic_disable_autorum();
}
});
The wp hook runs after WordPress has resolved the request. That matters because the AMP helper must not be called before the main query is available. The function checks also keep the site working when either integration is absent.
This disables automatic browser instrumentation. There is no newrelic_ignore_transaction() call: throwing away server-side performance data is a separate decision and normally unnecessary for this problem. Manually inserted browser scripts or tag-manager injections need to be removed at their own source.
Check the actual response
Clear the relevant page cache, request an AMP page, and inspect its source and AMP validation result. Then confirm that an ordinary page still has the expected browser instrumentation. A cached page can otherwise make a correct change look ineffective. AMP validation alone is not a promise of a particular search appearance or ranking.
References: New Relic's PHP API, AMP request detection and WordPress's wp hook.
Original version19 July 2016
Kept here for reference and earlier links. The updated guide above is the recommended starting point; older code may depend on retired services or different software versions.
If you're a pretty techy web dev worth your salt you'll love playing with new technologies. That may have led you down the path of trying out both New Relic for performance monitoring of servers and AMP - the new lightweight way of serving websites specifically for mobile.
In doing so you may find that your AMP pages are not valid, this is due to New Relic injecting JavaScript into the beginning of your webpages for its speed tracking purposes. Google/AMP will then not see your webpage as valid AMP markup due to this JavaScript - and as such you won't rank or gain any benefit from having AMP installed.
The easiest way to stop this if you're using the Wordpress AMP plugin is to go to Plugin Editor and add the following code to the top of amp/amp.php
if (extension_loaded('newrelic')) {
newrelic_disable_autorum();
newrelic_ignore_transaction();
}
newrelic_disable_autorum();
newrelic_ignore_transaction();
Keep exploring