在jQuery中使用PHP获取WordPress模板目录中存储的图像链接

在jQuery中使用PHP获取WordPress模板目录中存储的图像链接,jquery,wordpress,Jquery,Wordpress,我正努力想弄明白。我基本上只想在外部链接的末尾添加一个图像(external.png)。我把图像放在一个名为img的目录中,这个目录存储在我的wordpress主题中。如果我对图像的src是直接的,它可以工作,但我宁愿使用: <?php bloginfo('template_directory') ?> 当把它放在after()中不起作用时,我尝试了以下方法: $(document).ready(function() { var templateDir = "<?php

我正努力想弄明白。我基本上只想在外部链接的末尾添加一个图像(external.png)。我把图像放在一个名为img的目录中,这个目录存储在我的wordpress主题中。如果我对图像的src是直接的,它可以工作,但我宁愿使用:

<?php bloginfo('template_directory') ?>

当把它放在after()中不起作用时,我尝试了以下方法:

$(document).ready(function() {
var templateDir = "<?php bloginfo('template_directory') ?>";
$('a').filter(function() {
return this.hostname && this.hostname !== location.hostname;
}).after('<img src="' + templateDir + '/img/external.png" />');
$(文档).ready(函数(){
var templateDir=“”;
$('a').filter(函数(){
返回this.hostname&&this.hostname!==location.hostname;
}).在('')之后;
}))


但这也不起作用。有什么想法吗?提前谢谢

在wordpress中,将php变量插入javascript的正确方法是通过
wp\u localize\u script()
。在你的Functions.php(或者插件,随便什么)中

关键是,您必须在服务器上定义PHP变量,然后才能在客户端使用它们

或者,您可以使用ajax解决一些问题


Cheers

jQuery在客户端工作,因为它是JavaScript,而不是服务器。jQuery在呈现到浏览器后是什么样子的?(使用“查看源代码”并将jQuery的相关部分粘贴到问题中)。很乐意提供帮助-如果您认为这个答案是正确的,不要忘记“接受”它;D
<?php
$data = array( 'some_string' => __( 'Some string to translate' ) );
wp_localize_script( 'some_handle', 'object_name', $data );
?> 
<script>
alert(object_name.some_string); // alerts 'Some string to translate'
</script>