Pretty new to WordPress functions, so apologies if this is basic stuff.
I’ve designed a parent theme that registers and enqueues two scripts like so:
if ( !function_exists( 'scherzo_scripts' ) ) :
function scherzo_scripts() {
if (!is_admin()) {
wp_register_script( 'html5shiv', get_template_directory_uri() . '/js/html5.js');
wp_register_script( 'css3mediaqueries', get_template_directory_uri() . '/js/css3-mediaqueries.js');
wp_enqueue_script('html5shiv');
wp_enqueue_script('css3mediaqueries');
}
}
add_action('init', 'scherzo_scripts');
endif;
I’m finding that if I install a child theme the scripts don’t run. To try and force them to run I create a new functions.php
file in the child theme folder and add:
function scherzo_scripts() {
if (!is_admin()) {
wp_register_script( 'html5shiv', get_template_directory_uri() . '/js/html5.js');
wp_register_script( 'css3mediaqueries', get_template_directory_uri() . '/js/css3-mediaqueries.js');
wp_enqueue_script('html5shiv');
wp_enqueue_script('css3mediaqueries');
}
}
add_action('init', 'scherzo_scripts');
But no joy. Am I doing something wrong?
functions.php file of the child theme is loaded before the functions.php of the parent theme so it’s best to run the code at the hook after both themes are loaded. At the earliest at
after_setup_theme
hook so Change:to:
2023 Update:
WordPress Docs
/home/user/public_html/wp-content/themes/my_theme
get_template_directory() instead if you want the parent directory).
I’m not sure why your scripts won’t load when you install a child theme.
However, when you want to load scripts from a child theme you’ll want to use get_stylesheet_directory() instead of get_template_directory_uri().
The differnece between the two is that get_template_directory_uri() will always refer to the parent theme, whereas get_stylesheet_directory() will refer to the directory of the stylesheet being used. When using a Child theme it automatically will fetch the Child themes url.
Hope this helps, good luck!
See: https://developer.wordpress.org/reference/functions/get_stylesheet_directory/