在javascript中使用Wordpress PHP代码

在javascript中使用Wordpress PHP代码,javascript,php,wordpress,Javascript,Php,Wordpress,我想在JavaScript中使用PHP代码。大概是这样的: function offshownow(){ document.getElementById("test").src="<?php echo get_option('siteurl'), $plugin_dir; ?>/image.gif" } 函数offshownow(){ document.getElementById(“test”).src=“/image.gif” } 我该怎么办? 特别是它不起作用 在主

我想在JavaScript中使用PHP代码。大概是这样的:

function offshownow(){
    document.getElementById("test").src="<?php echo get_option('siteurl'), $plugin_dir; ?>/image.gif"
}
函数offshownow(){
document.getElementById(“test”).src=“/image.gif”
}
我该怎么办?
特别是它不起作用

在主题/插件的PHP代码中使用WordPress的函数
wp\u localize\u script
,将所需信息从服务器端移动到客户端。然后,在JavaScript中,引用已本地化的变量

按照上面几乎没有描述的用例,它将类似于

PHP:

JS:


您需要这样做,因为JavaScript和PHP不相关——JavaScript不能运行任何PHP代码。在这里,我们已经让PHP显式地将一些数据推送到JavaScript中,这样就可以在那里使用它,但是你不能只使用
alert(“”):(

只要javascript所在的文件是由PHP解析的,那就不应该是问题,你试过了吗,有问题吗,问题到底是什么,“我应该做什么”有点笼统。问题是什么,给出更多细节……错误???这段代码不起作用:(你是说我以正确的方式编写了代码?
wp_enqueue_script("php_vars");
wp_localize_script("php_vars", "php_vars", array(
    "my_url" => get_option('siteurl') . $plugin_dir
));
function offshownow(){
    document.getElementById("test").src = php_vars.my_url + "/image.gif";
}