3

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:

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.

2 Answers 2

1

You need to use get_template_directory_uri() function for get the theme folder path.then you can pass js/yourjsfile path name.

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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. It means that it would point to /wp-content/plugins directory, which is not where your theme is located.

You need to use get_template_directory_uri() instead. 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' );

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.