我有大约 300 个 WooCommerce 产品,其中纬度和经度信息作为自定义字段,我想将它们添加到使用 Leaflet 创建的 map 中。
我目前正试图为 map 内的每个产品创建标记,因为我没有正确获取产品信息。
这是我用于检索产品数据的 PHP 代码(我目前正在测试只有 4 个产品的类别,以使其更容易):
$products = wc_get_products( array( 'status' => 'publish', 'limit' => -1, 'product_cat' => 'talleres' ) );
在 JavaScript 方面,这是我正在使用的代码:
var locaciones = [
[ <?php foreach ( $products as $product ) { echo get_post_meta( $product->get_id(), 'coord_lat', true ); } ?>, <?php foreach ( $products as $product ) { echo get_post_meta( $product->get_id(), 'coord_long', true ); } ?>, "<?php foreach ( $products as $product ) { echo $product->get_title(); } ?>", {icon: iconoUrbe}, "https://permalink.com/", "https://i.imgur.com/xH761ML.jpg" ]
];
for (var i=0; i<locaciones.length; i++) {
var lat = locaciones[i][0];
var lon = locaciones[i][1];
var popupText = locaciones[i][2];
var icono = locaciones[i][3];
var permalink = locaciones[i][4];
var imagen = locaciones[i][5];
var locacionMarcador = new L.latLng(lat, lon);
var locacion = new L.marker(locacionMarcador, icono);
mapita.addLayer(locacion);
locacion.bindPopup("<div class='titulo'>" + popupText + "</div>" + "<br><a href='" + permalink + "' target='_blank' class='imgborde'>" + "<img src='" + imagen + "' width='250' height='141' />" + "</a><br><a href='" + permalink + "' target='_blank'>Más información</a>");
}
该代码输出以下纬度:
-26.910714-26.978776-26.968379-27.540683
该输出不起作用,因为当添加到 JavaScript 时, map 无法识别它,因为它在数组中看起来像这样:
[ -26.910714-26.978776-26.968379-27.540683, -68.036321-67.941395-67.505819-68.225849, "Taller de fotografía time-lapseTaller de fotografia nocturna de paisajeTaller de introducción a la fotografía digitalTaller de revelado con Lightroom Classic", {icon: iconoUrbe}, "https://permalink.com/", "https://i.imgur.com/xH761ML.jpg" ],
因此,我不需要将所有信息集中在一起,而是需要分别获取每个产品的纬度、经度等。
我还没有添加图标、永久链接和图像 URL 信息,因为它破坏了 map ,而且我无法检查任何调试内容。
最佳答案
您可以使用 json_encode(内置 php 函数)将内容放入 JavaScript 变量中。这将使事情更有条理,也许有助于解决您的问题。
<?php
$products = wc_get_products([
'status' => 'publish',
'limit' => -1,
'product_cat' => 'talleres'
]);
$locations = array_map(function ($product) {
/** @var WC_Product $product */
return [
'lat' => get_post_meta($product->get_id(), 'coord_lat', true),
'long' => get_post_meta($product->get_id(), 'coord_long', true),
'title' => $product->get_title(),
'icon' => '...',
'url' => '...',
'img_url' => '...',
// if easier, just include the popup html here and not the other stuff
'popup_html' => '',
];
}, $products);
?>
<script>
var locations = <?= json_encode($locations); ?>
// assuming you have jQuery. If not, use a for loop.
$.each(locations, function (index, location) {
console.log(location);
});
</script>
关于javascript - 检索 WooCommerce 产品数据并将其传递到 JavaScript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58946486/