在 WordPress 网站中添加足迹地图,能以直观的方式展示去过的地点,为网站增添个性化元素。下面将详细介绍通过创建短代码在 WordPress 中插入足迹地图的方法。
一、在 WordPress functions.php 添加短代码
有两种途径可以在 WordPress 中添加相关代码,你可以根据自身情况选择:
直接在主题的 functions.php 文件中添加:打开 WordPress 主题目录下的 functions.php 文件。这是一个对主题功能至关重要的文件,修改时务必小心。在文件中添加以下代码:
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');
使用 Code Snippets 插件添加:如果担心直接修改 functions.php 文件会出现问题,可以使用 Code Snippets 插件。在 WordPress 后台搜索并安装 “Code Snippets” 插件。安装激活后,在 WordPress 后台依次点击 “代码片段” - “添加新片段”。在新页面中,给代码片段起个描述性的标题,如 “插入足迹地图短代码”。将上述代码粘贴到 “代码” 文本框中,然后点击 “保存更改并激活” 按钮。
二、在文章中使用短代码
完成代码添加后,在撰写或编辑 WordPress 文章时,在文章内容需要插入足迹地图的位置输入[ custom_map ]
。保存或发布文章后,就能看到插入的足迹地图,地图上标记着预设的地点(上海、北京、深圳),点击标记会弹出包含地点名称和到访时间的弹窗。
三、注意事项
备份 functions.php 文件:在对 functions.php 文件进行修改前,一定要备份该文件。因为如果代码存在错误,可能导致网站无法正常访问或出现功能异常。可以通过 FTP 工具或网站主机的文件管理面板下载 functions.php 文件进行备份。
避免直接在文章中粘贴<script>代码:WordPress 出于安全考虑,可能会拦截直接粘贴在文章里的<script>
代码,导致地图无法正常显示。因此,通过 functions.php 文件或 Code Snippets 插件添加短代码更为可靠。
注:为了每次添加方便不在进入functions.php添加,我写了一个插件,后续会分享出来。