Adding event tags to links

3 posts by 2 authors in: Forums > CMS Builder
Last Post: August 29, 2016   (RSS)

By Toledoh - August 28, 2016

Hi All,

I'm wondering if there is some automated way of adding event tags to links created via the WYSIWYG field?

ie.  If a user created a link, added a title (Sample Title), then selected a class that I've added via the wysiwyg_custom.css (.trackThis), could I then have the outputted link be

<a href='linkURL' onClick="ga('send', 'event', { eventCategory: 'Internal Page Links', eventAction: 'click', eventLabel: '$recordTitle', eventValue: Sample Title});">

Cheers,

Tim (toledoh.com.au)

By Djulia - August 29, 2016 - edited: August 29, 2016

Hi Tim,

You can use DOMDocument::loadHTML

$doc = new DOMDocument;
$doc->loadHTML(utf8_decode('<div>'.$record['content'].'</div>'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  
// find all anchors
foreach ($doc->getElementsByTagName('a') as $anchor) {
  if ($anchor->hasAttribute('class') && $anchor->hasAttribute('title')) {
    $attr = $anchor->getAttribute('class');
    if ($attr != 'trackThis') { continue; }
    $anchor->setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Internal Page Links', eventAction: 'click', eventLabel: ".$anchor->textContent.", eventValue: Sample Title})");
  }
}
$html = utf8_encode($doc->saveHTML());
$new_html = preg_replace("/(^<div[^>]*>|<\/div>$)/i", "", $html);
echo $new_html;

LIBXML_HTML_NODEFDTD is only available in Libxml 2.7.8 and LIBXML_HTML_NOIMPLIED is available in Libxml 2.7.7...
http://www.php.net/manual/en/libxml.constants.php

Cheers,

Djulia