Adding Google Analytics to Wordpress' next_post_link function

佐手、 提交于 2019-12-10 19:27:43

问题


Working on setting up Google Analytics within a custom theme. I make use of the previous_post_link and next_post_link functions within my site to do some navigation pieces. Now I'm trying to add in some Google Analytics to those.

I've added this to my functions.php file:

add_filter('next_post_link', 'ga_next_post_link');
function ga_next_post_link($link) {
    $link = str_replace('" rel="next">', '" onclick="ga('send', 'event', 'NavNext', 'click');" rel="next">', $link);
    return $link;
}
add_filter('previous_post_link', 'ga_previous_post_link');
function ga_previous_post_link($link) {
    $link = str_replace('" rel="last">', '" onclick="ga('send', 'event', 'NavLast', 'click');" rel="last">', $link);
    return $link;
}

When I try that, I get a 500 error thrown back at me. If I replace the ga('...'); junk with test, it will load and work fine.

Anyone know why this is, and how I can fix it?


回答1:


Try escaping your quotes. Since you're using single quotes on str_replace() you have to escape the quotes in the function itself.

 $link = str_replace('" rel="next">', '" onclick="ga(\'send\', \'event\', \'NavNext\', \'click\');" rel="next">', $link);


来源:https://stackoverflow.com/questions/36479870/adding-google-analytics-to-wordpress-next-post-link-function

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