最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to add a custom javascript file to our theme

programmeradmin1浏览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');}
}

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 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 – tiago calado Commented Dec 21, 2021 at 16:46
Add a comment  | 

1 Answer 1

Reset to default 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).

发布评论

评论列表(0)

  1. 暂无评论