如题,js 获取 WordPress 主题目录函数,折腾主题有时候会用得上。
直接在页面中输出页面地址
适合 js 代码与 PHP 在同一文件。
<script>var themeurl="<?php bloginfo('template_directory') ?>"</script>
这样 themeurl 变量可以在页面中直接引用。
另外:下面的代码也可以把 PHP 中的变量传入 JS 内:
<?php $tester = "cyhour.com"; ?>
<script>
var test1=<?php echo "'$tester'"; ?>;
var test2="<?=$tester;?>";
</script>
参考:PHP+JavaScript+HTML变量之间赋值及传递、php变量赋值给js
检测 head 中 style.css 文件来获取目录
代码直接放在需要引用主题地址的 js 文件内。
function themeurl(){
var i=0,got=-1,url,len=document.getElementsByTagName('link').length;
while(i<=len && got==-1){
url=document.getElementsByTagName('link')[i].href;
got=url.indexOf('/style.css');
i++;
}
return url.replace(/style(.*)/,'');//替换掉 url 中的 style.css?ver=123456789 等字符
};
这个函数返回的就是你所用主题目录 URL(如:http:s//你的域名/wp-content/themes/你的主题/)。
推荐个小工具:正则表达式在线测试
原文:zww - js获取WordPress主题目录函数
Comments:0