Search code examples
javascriptwordpresswordpress-themingcustom-wordpress-pageswordpress-admin

Inserting Javascript into admin footer wordpress


I need to add Livechat widget on all WordPress admin pages (backend).

The Livechat JavaScript code is this:

<!-- Start of LiveChat (www.livechatinc.com) code -->
<script type="text/javascript">
window.__lc = window.__lc || {};
window.__lc.license = 12345678;
(function() {
  var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
  lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
})();
</script>
<noscript>
<a href="https://www.livechatinc.com/chat-with/10437202/" rel="nofollow">Chat with us</a>,
powered by <a href="https://www.livechatinc.com/?welcome" rel="noopener nofollow" target="_blank">LiveChat</a>
</noscript>
<!-- End of LiveChat code -->

Livechat has a plugin for the chat to work on the front-end pages. I actually wanted to add this code to every page of WordPress back-end.

I was thinking of putting it in the admin footer through the functions.php of my child theme, but I'm not sure how to put this code together.

The code I am inserting into the child theme is this:

function remove_footer_admin () {
    echo 'My footer text. Thank you WordPress for giving me this filter.';
}
add_filter( 'admin_footer_text', 'remove_footer_admin' );

Where should I put this code to work?


Solution

  • You can add JavaScript code in admin footer using admin_footer hook.

    If you also need to add same code on the front-end, then apply wp_footer hook too.

    Here is a complete code goes in child theme's functions.php:

    // Function to render LiveChat JS code
    function lh_add_livechat_js_code() {
    ?>
        <!-- Start of LiveChat (www.livechatinc.com) code -->
        <script type="text/javascript">
        window.__lc = window.__lc || {};
        window.__lc.license = YOUR_KEY; // use your license key here
        (function() {
          var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
          lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
          var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
        })();
        </script>
        <noscript>
        <a href="https://www.livechatinc.com/chat-with/10437202/" rel="nofollow">Chat with us</a>,
        powered by <a href="https://www.livechatinc.com/?welcome" rel="noopener nofollow" target="_blank">LiveChat</a>
        </noscript>
        <!-- End of LiveChat code -->
    <?php
    }
    add_action( 'admin_footer', 'lh_add_livechat_js_code' ); // For back-end
    add_action( 'wp_footer', 'lh_add_livechat_js_code' ); // For front-end