How to add an onclick function to wordpress menu item (For google cross domain tracking)

丶灬走出姿态 提交于 2020-01-06 02:58:09

问题


I am setting up google analytics cross domain tracking on my website. I know I need to change each link to include:

onclick="_gaq.push(['_link', 'http://mywebsite.com/']); return false;"

I can set this up and get everything working great on the majority of the site, save one menu item. I've tried the jinMenu plugin, but that busted a few things.

site: http://www.trukid.com

Any help is much appreciated.

PS - This looks like it's on the right track for helping me, but I'm not sure how to translate it to my issue (I know minimal JS)

<script>

$(document).ready(function() {

    // Forcing WordPress to accept GA clicks

    $('.menu-twitter').delegate('a', 'click', function(e) {
        e.preventDefault();
        _gaq.push(['_trackEvent', 'Button', 'click', 'Twitter button']);  
        var lnk = $(this).attr('href');
        setTimeout('document.location = "' + lnk + '"', 100);
    });

    $('.menu-facebook').next.delegate('a', 'click', function(e) {
        e.preventDefault();
        _gaq.push(['_trackEvent', 'Button', 'click', 'Facebook button']);
        var lnk = $(this).attr('href');
        setTimeout('document.location = "' + lnk + '"', 100);
    });

});

</script>

回答1:


For example:

<script>

$(document).ready(function() {
    $('#nav-main a ').click(function() {
    var p = $(this).attr('href');
    if (p.search(/.+mywebsite/) == -1){ 
        _gaq.push(['_link', 'http://mywebsite.com/']); return false;
    }       
    });
});

</script>

You don't need the "delegate" - that's necessary only when new links are created dynamically (links created via javascript have no events attached, delegate takes care of that). Replace nav-main with the id of your navigation an mywebsite with your domain.

The p.search bit makes sure that _link is only attached to the links that do not point to the domain the script runs on (since you need this only for links that go to your other domain).



来源:https://stackoverflow.com/questions/15494840/how-to-add-an-onclick-function-to-wordpress-menu-item-for-google-cross-domain-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!