WordPress.org

Ready to get started?Download WordPress

Forums

Google Analytics by Yoast
Filter to use for custom links (3 posts)

  1. magicroundabout
    Member
    Posted 1 year ago #

    Hi there,

    I'm having trouble with some downloads being tracked. I think it's to do with the fact that my download links are generated from post meta data. So I do something like:

    $url = get_post_meta( get_the_ID(), '_some_meta_var', true );
    printf('<a href="%s>%s</a>, $url, "My download");

    I'd assumed that GA4WP would use JavaScript to scan the page for links and inject the relevant "onClick" code, or just use a function that triggers on any anchor tag but it seems that it doesn't work this way.

    From looking at the GA4WP code it seems that you filter links in the_content (and various other places) and inject the tracking code there, for each link. This won't, obviously, apply to my custom download links.

    Is there, therefore, a recommended way of tracking my links. Perhaps by applying one of the GA4WP filters to my links before printing them. Something like:

    $url = get_post_meta( get_the_ID(), '_some_meta_var', true );
    $link = printf('<a href="%s>%s</a>, $url, "My download");
    if (class_exists('GA_Filter')) {
      $link = GA_Filter::the_content($link);
    }

    Is this the kind of thing I should be doing? Or is there a better way?

    Thanks

    http://wordpress.org/extend/plugins/google-analytics-for-wordpress/

  2. magicroundabout
    Member
    Posted 1 year ago #

    Minor correction in second code snippet - should be sprintf:

    $url = get_post_meta( get_the_ID(), '_some_meta_var', true );
    $link = sprintf('<a href="%s>%s</a>, $url, "My download");
    if (class_exists('GA_Filter')) {
      $link = GA_Filter::the_content($link);
    }
  3. magicroundabout
    Member
    Posted 1 year ago #

    Argh! This code was broken by a recent update to the plugin (your major code refactoring, I think.

    Made me realise that I was doing it wrong anyway because GA_Filter isn't a static class!

    Here's corrected code:

    `$url = get_post_meta( get_the_ID(), '_some_meta_var', true );
    $link = sprintf('%s, $url, "My download");
    global $yoast_ga;
    if (is_a($yoast_ga, 'GA_Filter')) {
    $link = $yoast_ga->the_content($link);
    }

Topic Closed

This topic has been closed to new replies.

About this Plugin

About this Topic