简体   繁体   中英

Wordpress: path to my img in a javascript file

I know it is good practice to register a javascript file in wordpress (functions.php). But how exactly is this done?

I used to do it this way in the head:

<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/script.js"></script>

Then in my script.js file i have 2 lines of code:

var openmenu = "assets/menu.svg";
var closemenu = "assets/close-menu.svg";

But when i move my wordpress site online, the svg's won't load. I know it has something to do with wp_enqueue_script but i can't seem to figure out how exactly...

Many thanks!

First you have to register your scripts, like this (on your theme's functions.php)

add_action('wp_enqueue_scripts', function(){
    wp_register_script('my-script', get_stylesheet_directory_uri() .'/js/my-script.js', array('jquery'), '3.14', true );
});

Where:

  • 'my-script' is an id for your script (whatever you want)
  • get_stylesheet_directory_uri() .'/js/my-script.js' it's the full URL to your script
  • array('jquery') are the dependencies for the script -- if there are no dependencies, just use an empty array() . If you're adding a new script that depends on the previously registered 'my-script' (or whatever "id" you used), you can use array('jquery', 'my-script')
  • '3.14' it's a version number for your script
  • true indicates that the script can be loaded on the footer (better for the page load speed)

Then, using the "id" for enqueued script:

add_action('wp_enqueue_scripts', function(){
    wp_register_script('my-script', get_stylesheet_directory_uri() .'/js/my-script.js', array('jquery'), '3.14', true );
    wp_localize_script('my-script', 'MyScript', array(
        'foo' => 'bar',
        'stuff' => get_option('quick_brown_fox'),
        'menu' => get_template_directory_uri() .'/img/menu.svg',
        'close_menu' => get_template_directory_uri() .'/img/close_menu.svg'
    ));
});

That way, whenever you load the "my-script" script, WordPress will create a "MyScript" javascript global that you can later use on your js file to get that value.

So, on your js, now you can use:

var closeMenuImgPath = MyScript.close_menu;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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