[英]How to pass variable of wp shortcode to JavaScript?
I have created a shortcode of google map in my theme. 我已经在主题中创建了Google地图的简码。 Here's all the code: 这是所有代码:
function shortcode_googlemap_view($atts){
extract(shortcode_atts(array(
"width"=>'',
"height"=>'',
"latitude"=>'',
"longitudinal"=>'',
),$atts));
return '<div id="map_view" style="width:'.$width.'px;height:'.$height.'px;"></div>';
}
add_shortcode("google_map","shortcode_googlemap_view");
JavaScript: JavaScript的:
function initialize()
{
var mapProp = {
center: new google.maps.LatLng(24.17310, 88.91905),
zoom:12,
panControl:true,
zoomControl:true,
mapTypeControl:true,
scaleControl:true,
streetViewControl:true,
overviewMapControl:true,
rotateControl:true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_view"),mapProp);
};
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now I want to pass the value of "latitude" for 24.17310 and "longitudinal" for 88.91905 in JavaScript 现在我想在JavaScript中传递24.17310的“纬度”和88.91905的“纵向”值
center: new google.maps.LatLng(24.17310, 88.91905),
You have several options: 您有几种选择:
Generate the Javascript code dynamically, using PHP, inside the shortcode function/class. 在短代码函数/类中使用PHP动态生成Javascript代码。 Then you can use the shortcode attributes in PHP to generate the needed Javascript code. 然后,您可以在PHP中使用shortcode属性生成所需的Javascript代码。
Refactor the initialize function a bit, so that it accepts lat, long as input args, and use them to properly init the map. 稍微重构初始化函数,以便它接受lat(只要是输入参数),并使用它们正确地初始化映射。
Thanks for the answer. 感谢您的回答。 I'm returning now a in my plugin function and it works: 我现在在插件函数中返回a,它可以正常工作:
function loadMyPlugin($atts) {
extract(shortcode_atts(array(
"myValue" => 'false'
), $atts));
include dirname( __FILE__ ) . './myPlugin-ui.php';
return '<script>var myValue = "'.$atts['myValue'].'"</script>';
}
But this looks not like a clean solution. 但这似乎不是一个干净的解决方案。 I would like to use the wp_localize_script()
function but I was able to do that. 我想使用wp_localize_script()
函数,但是我能够做到这一点。 An example for the second solution would be great. 第二种解决方案的例子很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.