0

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');}
}
3
  • 1
    Why the if (! function_exists('custom_jsfiles')) { guard?
    – Rup
    Commented Dec 21, 2021 at 16:44
  • 1
    You can also use get_theme_file_uri to get the path to the file without hard-coding the /wp-content/ bit.
    – Rup
    Commented Dec 21, 2021 at 16:45
  • got it now, need to register it first and then use the wp_enquere_script Commented Dec 21, 2021 at 16:46

1 Answer 1

0

Having 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).

3
  • Also the Rup answer is correct, using the get_theme_file_uri is more commonly used, the thing is that I am using this in a plugin. Commented Dec 21, 2021 at 16:51
  • 1
    You don’t need to register scripts before enqueueing them. That’s not the issue. Commented Dec 22, 2021 at 1:33
  • Had found the reason, wrong path and funtion parameteres missing. Thanks! Commented Jan 26, 2022 at 20:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.