1

I'm struggling to understand how to enqueue an external js file with some widget code within Wordpress. For example: there is a Frontapp chatbot that has to have the following code placed into the end of the tag with my theme:

<script src="https://chat-assets.frontapp.com/v1/chat.bundle.js"></script>
<script>
  window.FrontChat('init', {chatId: '0xxxx', useDefaultLauncher: true});
</script>

How would I enqueue this since there's both an external link & snippet of Js?

  • Does this answer your question? [How to Enqueue JS Links in WordPress?](https://stackoverflow.com/questions/31217412/how-to-enqueue-js-links-in-wordpress) – Howard E Jul 27 '22 at 23:47

2 Answers2

0

You can use wp_enqueue_script for external scripts as well as wp_add_inline_script for inline scripts.

In your case that would be.

wp_enqueue_script('my-chat-assets', 'https://chat-assets.frontapp.com/v1/chat.bundle.js');
wp_add_inline_script('my-chat-assets', "window.FrontChat('init', {chatId: '0xxxx', useDefaultLauncher: true});");

Those lines should appear in wp_enqueue_scripts hook like all other enqueued scripts. If you want it at the footer, add true to the footer parameter. So all in all:

add_action('wp_enqueue_scripts', function () {
    wp_enqueue_script('my-chat-assets', 'https://chat-assets.frontapp.com/v1/chat.bundle.js', [], false, true);
    wp_add_inline_script('my-chat-assets', "window.FrontChat('init', {chatId: '0xxxx', useDefaultLauncher: true});");
});
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Ty for this! Been trying to play around with using wp_add_inline_script but nothing is working on my end. Can I just use: `wp_register_script( 'my-chat-assets', 'https://chat-assets.frontapp.com/v1/chat.bundle.js', [], '', true ); wp_enqueue_script( 'my-chat-assets'); wp_add_inline_script('my-chat-assets', "window.FrontChat('init', {chatId: '0be7f8835374548fada14d2ca772a83a', useDefaultLauncher: true});"); ` for it to appear in my footer or do I need an add_action as well? – teresawithoutah Jul 28 '22 at 00:00
0

I hope this will solve your problem.

add_action('wp_footer', function () {
    wp_enqueue_script('my-chat-assets', 'https://chat-assets.frontapp.com/v1/chat.bundle.js', [], false, true);
    wp_add_inline_script('my-chat-assets', "window.FrontChat('init', {chatId: '0xxxx', useDefaultLauncher: true});");
});