简体   繁体   English

外部JavaScript没有加载在Wordpress中

[英]External javascript not loading in Wordpress

I'm trying to load a custom js file on wordpress, I've upload to my javascript theme folder and I'm using the following code in functions.php but I can't make it work: 我正在尝试在wordpress上加载自定义js文件,我已上传到我的javascript主题文件夹,我在functions.php中使用以下代码,但我无法使其工作:

function wpb_adding_scripts() {
    wp_register_script('service-graph', plugins_url('js/service-graph.js', __FILE__), array('jquery'),'1.1', true);
    wp_enqueue_script('service-graph');
}

add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' ); 

Thank you. 谢谢。

You need to use get_template_directory_uri() function for get the theme folder path.then you can pass js/yourjsfile path name. 您需要使用get_template_directory_uri()函数来获取主题文件夹路径。然后您可以传递js / yourjsfile路径名。

Try below code 试试下面的代码

<?php

    function wpb_adding_scripts() {
    wp_register_script('service-graph', get_template_directory_uri() . '/js/service-graph.js', array('jquery'),'1.1', true);
    wp_enqueue_script('service-graph');
    }

    add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );  
    ?>

Jfyi - if you put anything in your current active theme folder you must need to use get_template_directory_uri() function as its return path to your theme directory. Jfyi - 如果您在当前活动主题文件夹中放置任何内容,则必须使用get_template_directory_uri()函数作为其主题目录的返回路径。

The problem is that you're using a wrong function to retrieve theme's folder. 问题是你使用了错误的函数来检索主题的文件夹。

plugins_url() is used for plugins, as you could guess from its name. plugins_url()用于插件,你可以从它的名字猜测。 It means that it would point to /wp-content/plugins directory, which is not where your theme is located. 这意味着它将指向/wp-content/plugins目录,这不是您的主题所在的位置。

You need to use get_template_directory_uri() instead. 您需要使用get_template_directory_uri() Note that this function does not return a trailing slash / following the directory address, so you need to add it to the beginning of your path. 请注意,此函数不会返回目录地址后面的尾部斜杠/ ,因此您需要将其添加到路径的开头。

So here's how your code should look like: 所以这是你的代码应该是这样的:

function wpb_adding_scripts() {
    wp_register_script('service-graph', get_template_directory_uri() . '/js/service-graph.js', array('jquery'), '1.1', true);
    wp_enqueue_script('service-graph');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM