Open djurnamn opened 5 years ago
we could do something like this in functions/actions.php
functions/actions.php
function bolts_wp_enqueue_scripts() { if (false != $analytics_id = get_field('analytics_id', 'option')) { wp_enqueue_script('analytics', 'https://www.googletagmanager.com/gtag/js?id=' . $analytics_id, null, null, false); wp_add_inline_script('analytics', "window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '" . $analytics_id . "');"); } } add_action('wp_enqueue_scripts', 'bolts_wp_enqueue_scripts');
to add async attribute to the script, we can add this filter:
function add_async_attr($tag) { if (strpos($tag, 'googletagmanager') == true) { return str_replace(' src', ' async="async" src', $tag); } return $tag; } add_filter('script_loader_tag', 'add_async_attr', 10);
also found a function to validate google analytics ids that we can use instead of calling get_field directly: return (bool) preg_match('/^ua-\d{4,10}(-\d{1,4})?$/i', $str); source
get_field
return (bool) preg_match('/^ua-\d{4,10}(-\d{1,4})?$/i', $str);
we could do something like this in
functions/actions.php
to add async attribute to the script, we can add this filter:
also found a function to validate google analytics ids that we can use instead of calling
get_field
directly:return (bool) preg_match('/^ua-\d{4,10}(-\d{1,4})?$/i', $str);
source