How to add custom JavaScript in WordPress site

February 13, 2024 / WordPress

This guide explains how to add custom JavaScript to a WordPress site. Adding custom JavaScript to a WordPress site can be beneficial for various reasons, such as enhancing user experience, adding custom functionality, integrating third-party services, or making design modifications that cannot be achieved with CSS alone.

Follow the steps for adding custom javascript in WordPress without plugin –

  1. Create a JavaScript –
    First, you will have to create a JavaScript file with your custom code. You can use any text editor to build this file. Remember to save it with “.js” extension. For example- “custom.js”.
  2. Upload the JavaScript File-
    1. The second step is to upload the JavaScript file to your WordPress site. This can be done by visiting your WordPress dashboard and navigating to Media > Add New Media File.
      add new media file
    2. Upload your JavaScript file here.
      Add custom javascript
  3. Copy the File URL –
    After uploading the file, copy the URL of the JavaScript file. You can find this by clicking on the file in the Media Library and copying the URL from the right-hand side.
  4. Add the JavaScript to Your Theme –
    Now, you will have to add the JavaScript to your WordPress theme. You can do this by editing your theme’s “functions.php” file. You can access this file by going to Appearance > Theme File Editor in your WordPress dashboard.
    Theme file editor
  5. Enqueue the Script-
    In the functions.php file, you will need to sequence the JavaScript file you uploaded.

    Add the following code to the file –

    function custom_scripts() {
     'URL_OF_YOUR_JAVASCRIPT_FILE', array(), null, true); 
    add_action('wp_enqueue_scripts', 'custom_scripts');

    Replace “URL_OF_YOUR_JAVASCRIPT_FILE” with the URL you copied in the third step.

  6. Save the Changes –
    Finally, save the changes to your functions.php file.

That is it! Your custom JavaScript should now be added to your WordPress site. You can test it by adding some code to your custom.js file and checking if it works on your site.

Adding a custom JavaScript to your WordPress site can help to enhance functionality of your site. However, if you want to include PHP code using a plugin, check out our guide on How to add PHP code using a plugin for detailed instructions. It will help you further customise your site and that meet your specific requirements with ease.

Dominos Search