簡體   English   中英

如何將wp shortcode的變量傳遞給JavaScript?

[英]How to pass variable of wp shortcode to JavaScript?

我已經在主題中創建了Google地圖的簡碼。 這是所有代碼:

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的:

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>

現在我想在JavaScript中傳遞24.17310的“緯度”和88.91905的“縱向”值

center: new google.maps.LatLng(24.17310, 88.91905),

您有幾種選擇:

  1. 在短代碼函數/類中使用PHP動態生成Javascript代碼。 然后,您可以在PHP中使用shortcode屬性生成所需的Javascript代碼。

  2. 稍微重構初始化函數,以便它接受lat(只要是輸入參數),並使用它們正確地初始化映射。

感謝您的回答。 我現在在插件函數中返回a,它可以正常工作:

function loadMyPlugin($atts) {

    extract(shortcode_atts(array(

        "myValue" => 'false'

    ), $atts));

    include dirname( __FILE__ ) . './myPlugin-ui.php';

    return '<script>var myValue = "'.$atts['myValue'].'"</script>';
} 

但這似乎不是一個干凈的解決方案。 我想使用wp_localize_script()函數,但是我能夠做到這一點。 第二種解決方案的例子很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM