Child Theme Authoring: Including Scripts & PHP Files
Enqueuing JavaScript
Any new script files should be placed in your child theme’s assets\ js folder, then enqueued using wp_enqueue_script . This works just like stylesheets:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
if( ! function_exists( 'layers_child_scripts' ) ) { function layers_child_scripts() { wp_enqueue_script( 'layers-child' . '-custom', get_stylesheet_directory_uri() . '/assets/js/theme.js', array( 'jquery', // make sure this only loads if jQuery has loaded ) ); // Custom Child Theme jQuery } } add_action('wp_enqueue_scripts', 'layers_child_scripts'); |
In the above example, we have specifically hooked wp_enqueue_scripts to ensure WordPress loads it in the best place (usually after the parent theme scripts in the header). We have also given it a dependency on ‘jquery’ to ensure it does not load unless jQuery is available.
You may want to include other script libraries that are more appropriately loaded into the footer. You can hook wp_footer to achieve that:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
if( ! function_exists( 'layers_child_footer_scripts' ) ) { function layers_child_footer_scripts() { wp_enqueue_script( 'layers-child' . '-lightbox', get_stylesheet_directory_uri() . '/assets/js/lightbox.js', array( 'jquery', // make sure this only loads if jQuery has loaded ) ); // Custom Child Theme jQuery } } add_action('wp_footer', 'layers_child_footer_scripts'); |
To modify a core Layers script, such as the slider, for example, you cannot copy this script to your child and attempt to load your modified version over the core. Instead, reference the script APIs and include the appropriate jQuery snippets for adjusting any arguments the script accepts and add these to your theme.js. APIs are linked from About Layers.
Including PHP Files
If you are housing a group of code in a separate PHP file from the functions.php, or need to reference a ready-made PHP library stored in your child theme directory structure, you must use require_once($path) from the functions.php to help WordPress find the file.
1 |
require_once( get_stylesheet_directory() . '/assets/my_filters.php' ); |
When defining the path, you would use get_stylesheet_directory() instead of get_stylesheet_directory_uri() to return the full server path to your child theme directory.