I add custom css files to my theme, but when I try to do the same for the javascript files, they dont seem to work, this means that the javascript on the html files is working properlly, but if I transfer it to the custom javascript file it doesnt. Am I adding the custom javascript file correctly to wordpress?
if (! function_exists('custom_jsfiles')) {
add_action('wp_enqueue_scripts', 'custom_jsfiles');
function custom_jsfiles() {wp_enqueue_script('custom_js', home_url().'/wp-content/themes/mytheme/custom-js.js');}
}
I add custom css files to my theme, but when I try to do the same for the javascript files, they dont seem to work, this means that the javascript on the html files is working properlly, but if I transfer it to the custom javascript file it doesnt. Am I adding the custom javascript file correctly to wordpress?
if (! function_exists('custom_jsfiles')) {
add_action('wp_enqueue_scripts', 'custom_jsfiles');
function custom_jsfiles() {wp_enqueue_script('custom_js', home_url().'/wp-content/themes/mytheme/custom-js.js');}
}
Share
Improve this question
edited Dec 21, 2021 at 17:22
fuxia♦
107k38 gold badges255 silver badges459 bronze badges
asked Dec 21, 2021 at 16:40
tiago caladotiago calado
6324 silver badges17 bronze badges
3
|
1 Answer
Reset to default 0Having this issue for months and I got it now running when I posted the question here. the issue is that the wp_enqueue_script needs to have the script file register first. So I have it working this way!
if (! function_exists('custom_jsfiles')) {
add_action('wp_enqueue_scripts', 'custom_jsfiles');
function custom_jsfiles() {
wp_register_script('custom_js', get_theme_file_uri().'/mytheme/custom-js.js');
wp_enqueue_script('custom_js');
}
}
########################
updating the answer, the path wasnt correct, also has jacob said, no need to register them And now its working
function ad_ficheiros(){
wp_enqueue_script('custom_js', get_template_directory_uri().'/inc/custom-js.js', array(), '1.15', true);
}
add_action('wp_enqueue_scripts', 'ad_ficheiros');
here the file is on a folder called inc inside the themes folder, also added two more parameters, the file version and if it is to be shown in the header or footer(false or true).
if (! function_exists('custom_jsfiles')) {
guard? – Rup Commented Dec 21, 2021 at 16:44