Search code examples
javascriptwordpressfunctionshortcode

How to Add HTML & Javascript to Wordpress Shortcode?


I have a snippet of HTML that I would like to make into a Wordpress shortcode. This is the snippet.

<div class="small-12 large-7 columns">
<article id="text-39" class="panel widget widget_text">         
    <div class="textwidget">
        <div class="row">
            <div class="h3 regular-font">Have Questions?</div>
            <div class="h5">TALK TO US 800.810.8412</div>
            <a href="http://www.oakwoodsys.com/email-us"><div class="button help-email left">Email Us</div></a>
            <!-- BEGIN OLARK CHAT LINK -->
            <a href="javascript:void(0);" onclick="olark('api.box.expand')"><div class="button help-chat left">Chat Now</div></a>
            <!-- END OLARK CHAT LINK -->
        </div>
    </div>
</article>
</div>

I've added this to my functions.php and it outputs the code properly when I add [chat] to a page in Wordpress.

// Chat/Email Shortcode
  function chat_shortcode() {
    return '<div class="small-12 large-7 columns">
<article id="text-39" class="panel widget widget_text">         
    <div class="textwidget">
        <div class="row">
            <div class="h3 regular-font">Have Questions?</div>
            <div class="h5">TALK TO US 800.810.8412</div>
            <a href="http://www.oakwoodsys.com/email-us"><div class="button help-email left">Email Us</div></a>
            <!-- BEGIN OLARK CHAT LINK -->
            <a href="#">Chat Now</div></a>
            <!-- END OLARK CHAT LINK -->
        </div>
    </div>
</article>
</div>';
    }
    add_shortcode('chat', 'chat_shortcode');

However, when I change the live chat link from # to javascript:void(0);" onclick="olark('api.box.expand'), the entire site breaks. How can I make the link work properly?


Solution

  • Your return statement opens and closes using '' so when you use them in your onclick your break the syntax (you close the return statement).

    Try this,

    onclick="olark(\'api.box.expand\')"