0

I am trying to enqueuer a script after registering it but I am getting an error.

This is the script:

function _test() {
    console.log("Test");
}

That's the PHP:

function fsg_shortURL() {
    echo "Funtion Called";
    wp_register_script('_test','/wp-content/themes/theme-child/js/test.js');
    wp_enqueue_script('_test');
}

add_shortcode( 'fsg', 'fsg_shortURL' );

The console's suppouse to log Test but nothing happens..

Thanks!

2 Answers 2

1

Simply you've to call the function to execute it:

function _test() {
  console.log("Test");
}
_test();
2
  • It works. Thanks but why is that? I thought wp_enqueue_script('_test'); is suppose to call the function is it not?
    – Omer
    Jul 31, 2018 at 8:19
  • no, you're including a .js script called test.js assigning it an id _test ( you can see inspecting the source in the head section) but the function _test() of the .js file itself must be executed by javascript.. probably the over-usage of "test" may have confused you, so maybe change the js function to console_test() and execute it leaving the rest unchanged to better understand Jul 31, 2018 at 8:25
0

To add a file located in a directory of the active theme, you have to use https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri

wp_register_script(
      "idScript"
    , get_stylesheet_directory_uri() . "/js/script.js"
);

In you question, you speak about a shortcode.
It's better to store shortcode in a plugin. then, you can get the file URL with https://codex.wordpress.org/Function_Reference/plugins_url

wp_enqueue_script(
     "pluginScript"
    , plugins_url("js/script.js", __FILE__)
);

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.