javascriptphpwordpresswoocommercewp-enqueue-scripts

Javascript and Wordpress Uncaught SyntaxError using wp_enqueue_script on single product page of woocommerce


I'm no good at javascript but I think this code is right because it is just copy and paste from Zopim website and it was working before I tried to use their widget in a different approach.

functions.php

<?php
if ( is_product()) {
    function wpa_enqueue_scripts() {
        wp_enqueue_script( 'wpa-main-js', get_theme_file_uri( 'js/zopim.js' ), [], null, true );
    }

    add_action( 'wp_enqueue_scripts', 'wpa_enqueue_scripts', 100 );
}

I am having another issue with the code above. I can't get the script file to load on products page. It only work if I remove the if conditional.

zopim.js

<script type="text/javascript">
window.$zopim||(function(d,s){var z=$zopim=function(c){z._.push(c)},$=z.s=
d.createElement(s),e=d.getElementsByTagName(s)[0];z.set=function(o){z.set.
_.push(o)};z._=[];z.set._=[];$.async=!0;$.setAttribute("charset","utf-8");
$.src="https://v2.zopim.com/?3eGZHNIx48cV45BpV2eeQ5nlDBvLzS0P";z.t=+new Date;$.
type="text/javascript";e.parentNode.insertBefore($,e)})(document,"script");
</script>

This script give me this error:

"Uncaught SyntaxError: expected expression, got '<'" and I have no idea why.


Solution

  • "It only work if I remove the if conditional."

    1. I'd write the if statement inside the wp_enqueue_scripts hook. Like so:
    add_action( 'wp_enqueue_scripts', 'wpa_enqueue_scripts');
    
    function wpa_enqueue_scripts()
    {
        if ( is_product()) 
        {
            wp_enqueue_script( 'wpa-main-js', get_theme_file_uri( 'js/zopim.js' ), [], null, true );
        }
    } 
    

    "This script give me this error "Uncaught SyntaxError: expected expression, got '<'" and I have no idea why."

    1. You don't need script tags in your javascript file. So you could go ahead and remove <script type="text/javascript"> and </script>.

    Let me know if you could get it to work.