Skip to content

Instantly share code, notes, and snippets.

@pshapiro
Last active February 23, 2017 02:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pshapiro/b8ed9183c69c104c4233456e08cb1a6d to your computer and use it in GitHub Desktop.
Save pshapiro/b8ed9183c69c104c4233456e08cb1a6d to your computer and use it in GitHub Desktop.
Sample WordPress theme functions.php modification to generate Client ID
// Source: https://www.simoahava.com/analytics/google-analytics-client-id-amp-pages/
// REST API for GTM container
add_action( 'rest_api_init', function() {
register_rest_route(
'amp-gtm',
'/amp.json',
array(
'methods' => 'GET',
'callback' => 'retrieve_gtm_json',
)
);
});
// Generate random Client ID
function generate_ga_client_id() {
return rand(100000000,999999999) . '.' . time();
}
// Set cookie to expire in 2 years
function getCookieExpirationDate() {
return date('D, j F Y H:i:s', time() + 60*60*24*365*2);
}
// Callback for the GET request
function retrieve_gtm_json( $data ) {
/* Get the hostname of the request origin, and parse it for the
* pure domain name. */
$domain = explode(':', $data->get_header('Host'))[0];
$domainName = str_replace('www.', '', $domain);
// Get the number of parts in the domain name
$domainLength = count(explode('.', $domainName));
/* Check if the browser already has the _ga cookie.
* If not, generate a new cookie. */
$cid = $_COOKIE['_ga'];
if (!isset($cid)) {
$cid = "GA1.{$domainLength}." . generate_ga_client_id();
}
/* Store the actual Client ID (last two numbers) of the
* _ga cookie value in the $cidNumber variable */
$cidNumber = preg_replace('/^GA.\.[^.]+\./','',$cid);
// Get all HTTP request parameters
$query = $_SERVER['QUERY_STRING'];
/* Fetch the actual GTM container, by passing the valid query parameters from
* the original request. */
$container = file_get_contents("https://www.googletagmanager.com/amp.json?{$query}");
// Replace the CLIENT_ID(AMP_ECID_GOOGLE) string with ${clientId}
$container = str_replace('CLIENT_ID(AMP_ECID_GOOGLE)','${clientId}', $container);
// Add the clientId to the "vars" object in the container JSON.
$container = json_decode($container);
$container->vars->clientId = $cidNumber;
// Build a new HTTP response from the modified configuration file.
$response = new WP_REST_RESPONSE( $container );
// Add the required headers (Set-Cookie, most importantly) to the Request
$response->header( 'Set-Cookie', "_ga={$cid}; Path=/; Expires=" . getcookieExpirationDate() . " GMT; Domain={$domainName};");
$response->header( 'Access-Control-Allow-Origin', 'https://cdn.ampproject.org');
// Remember to check the protocol and change to http if that's where your domain is
$response->header( 'AMP-Access-Control-Allow-Source-Origin', "https://{$domain}");
$response->header( 'Access-Control-Expose-Headers', 'AMP-Access-Control-Allow-Source-Origin');
// Return the HTTP response.
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment