Analytics & Testing

WordPress: Overwrite a Shortcode From a Parent Theme in Your Child Theme

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="" 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!

Douglas Karr

Douglas Karr is the founder of the Martech Zone and a recognized expert on digital transformation. Douglas has helped start several successful MarTech startups, has assisted in the due diligence of over $5 bil in Martech acquisitions and investments, and continues to launch his own platforms and services. He's a co-founder of Highbridge, a digital transformation consulting firm. Douglas is also a published author of a Dummie's guide and a business leadership book.

Related Articles

What do you think?

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Adblock Detected

Martech Zone is able to provide you this content at no cost because we monetize our site through ad revenue, affiliate links, and sponsorships. We would appreciate if you would remove your ad blocker as you view our site.