WordPress Snippets

Code Snippet

To enqueue a JavaScript file in WordPress, you use the wp_enqueue_script function in your theme’s functions.php file.

PHP

Place the following code towards the top of your child theme’s functions.php document.

<?php
function custom_scripts() {
    // register and enqueue the script like this for a theme:
    wp_enqueue_script( 'my-theme-script', get_template_directory_uri() . '/js/custom-script.js', array(), '1.0.0', true );

    // if you need to add jQuery as a dependency, you can do it like this:
    wp_enqueue_script( 'my-theme-script', get_template_directory_uri() . '/js/custom-script.js', array('jquery'), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'custom_scripts' );
?>

Note

my-theme-script can be named to make sense for your theme. Also, make sure the path ‘/css/external-style.css’ points to your external document and is named appropriately.

Note

All modifications to a theme or plugin should be made by creating a child theme and placing the changes there. Changes made to the parent theme will be overwritten the next time it updates.


WordPress Notes:

  • All modifications to a theme or plugin should be made by creating a child theme and placing the changes there; changes made to the parent theme will be overwritten the next time it updates

We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.