简体   繁体   中英

How do I refer to the root Wordpress directory INSIDE a Javascript file

I've got a javascript file and somewhere within the code I have this line:

$(".section-divider.ornament").append('<img src="wp-content/themes/blackandwhite/img/divider-glyph.png" alt="" />');

I know it's not best practice to hard code in the directory like that, but I don't know how else to do it since: a) as far as I know, PHP doesn't work within JS files. b) leaving it as "img/divider-glyph.png" (I've tried both with and without a leading '/') doesn't work either

I don't really like Wordpress so I keep my distance but I believe you can use this function to get the Wordpress base installation directory:

<?php
get_bloginfo('wpurl');
?>

You can use that to add this information to the DOM, for instance the <body> tag:

<body data-base-dir="<?php echo get_bloginfo('wpurl'); ?>">

Then your JS could read this information:

var baseDir = $("body").data("data-base-dir");

Note than jQuery's .data() method will only cache data-* attributes that exist when jQuery loads, so updating an attribute or adding it after jQuery loads will require using .attr("data-*") .

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