Well, it’s been quite a while since I’ve shared some tips on programming in WordPress. Lately, I’ve been back on the bench deploying code for all of our clients and it’s been fun to get back into the swing of things. You may have noticed the new Marketing Whitepaper integrations throughout the site – that was quite a fun project!
Today, I had a different issue. Many of our clients have buttons implemented through parent theme shortcodes. One of our partners at Elevated Marketing Solutions asked if we could do some event tracking on the buttons since they were great call-to-actions throughout the sites. Shortcode buttons are nothing more than an anchor tag that’s designed a bit more eloquently using a series of classes that are populated by the shortcode options.
Because of this, we needed to add an onclick event to the anchor text to register an event. Here’s what it might look like:
<a href="https://martech.zone/partner/dknewmedia/" class="button blue medium" onClick="ga('send', 'event', 'button', 'Click', 'Home Button');">Home Button</a>
The problem, of course, is that there’s a shortcode in place in our parent theme and we don’t want to edit a parent theme. And, since the shortcode is deployed across content all over the site, we also don’t want to create a new shortcode.
The solution is pretty slick. The WordPress API allows you to remove a shortcode! So, in our child theme, we can remove the shortcode, then replace it with our new shortcode function:
add_action( 'after_setup_theme', 'calling_child_theme_setup' );
function calling_child_theme_setup() { remove_shortcode( 'old_button_function_in_parent_theme' ); add_shortcode( 'button', 'new_button_function_in_child_theme' ); }
function new_button_function_in_child_theme( $atts, $content = null ) { ... your new shortcode is here... }
In my new button function (in my Child Theme’s functions.php), I rewrote the shortcode function to append a dynamic event onClick event. The output works beautifully and is now tracking in Google Analytics!