Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

google analytics option field group #70

Open
djurnamn opened this issue Oct 30, 2019 · 0 comments
Open

google analytics option field group #70

djurnamn opened this issue Oct 30, 2019 · 0 comments

Comments

@djurnamn
Copy link
Member

djurnamn commented Oct 30, 2019

we could do something like this in 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant