可以创建一个短代码,将地图嵌入到文章中。
1. 在 WordPress functions.php 添加短代码
在 主题的 functions.php 文件(或使用 Code Snippets 插件)添加以下代码:
function custom_map_shortcode() { ob_start(); ?> <div id="map" style="height: 500px;"></div> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" /> <script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> document.addEventListener('DOMContentLoaded', function() { const isMobile = window.innerWidth <= 768; var map = L.map('map').setView([35.86166, 104.195397], isMobile ? 3 : 4); L.tileLayer('https://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}', { subdomains: ["1", "2", "3", "4"], attribution: '© 高德地图', minZoom: 2, maxZoom: 18 }).addTo(map); const footprints = [ {lat: 31.230416, lng: 121.473701, title: '上海', desc: '2023年夏天到访'}, {lat: 39.904200, lng: 116.407396, title: '北京', desc: '2023年冬天到访'}, {lat: 22.543096, lng: 114.057865, title: '深圳', desc: '2024年春节到访'} ]; footprints.forEach(point => { L.circleMarker([point.lat, point.lng], { radius: isMobile ? 5 : 7, fillColor: "#FF4081", color: "#fff", weight: 2, opacity: 1, fillOpacity: 0.8 }).addTo(map) .bindPopup(`<h3>${point.title}</h3><p>${point.desc}</p>`, { closeButton: false }); }); }); </script> <?php return ob_get_clean(); } add_shortcode('custom_map', 'custom_map_shortcode');
2. 在文章中使用短代码
在 WordPress 文章的内容中添加:
custom_map两边加上[ ]

效果:
注意事项
- functions.php 修改时,请先备份,避免改错导致网站崩溃。
- WordPress 可能拦截 <script> 代码,所以建议使用 functions.php 添加短代码,而不是直接粘贴到文章里。