在听到歌词时候,总是忍不住跟着轻轻哼唱起来。但是,当前播放器只能够展示一行让我很是不舒服,如果想要自己唱或者提前构思歌词变得非常困难。恰好想了解网站运转机制和高级功能,就实现了一个调用接口显示歌词的界面,也对这个wordpress底层有了一点了解。
实现步骤
搜索后发现,WordPress支持一种简码,你可以把函数注册上去,然后调用简码使用。在外观->主题文件编辑器里面,有个funcitons.php,可以写好函数后add_shortcode
导出。
整了个简单的网易歌词搜索,但是话说大部分精力其实都在调整html样式上,以后有机会再来修改吧
function fetch_lyrics_shortcode() {
return '
<div id="search-container">
<input type="text" id="song-search" placeholder="输入歌曲名..." />
<button onclick="searchSongs()">搜索</button>
</div>
<div id="dynamic-content"></div> <!-- 动态生成的内容将插入这里 -->
<script>
const apiKey = "042648db043c49ce8b101721df4078af";
const searchApiUrl = "https://myhkw.cn/open/music/search?key=" + apiKey + "&type=wy&page=1&limit=10&format=1";
const lyricsApiUrl = "https://myhkw.cn/open/music/lrc?key=" + apiKey + "&id=";
const picApiUrl = "https://myhkw.cn/open/music/pic?key=" + apiKey + "&id=";
async function searchSongs() {
const query = document.getElementById("song-search").value.trim();
if (!query) {
alert("请输入歌曲名!");
return;
}
const dynamicContent = document.getElementById("dynamic-content");
dynamicContent.innerHTML = `
<div id="search-results" style="margin-top: 20px; height: 300px; overflow-y: auto; border: 1px solid #ddd; padding: 10px;">搜索中...</div>
<div id="lyrics-container" style="margin-top: 20px;">请输入歌曲名并点击搜索。</div>
`;
try {
const wyResults = await fetch(`${searchApiUrl}&name=${encodeURIComponent(query)}`).then(res => res.json());
displaySearchResults(wyResults);
} catch (error) {
document.getElementById("search-results").innerText = "搜索失败:" + error.message;
}
}
async function displaySearchResults(wyResults) {
const container = document.getElementById("search-results");
const songs = [];
if (wyResults && wyResults.code === 1 && wyResults.data) {
songs.push(...wyResults.data.map(song => ({ ...song, platform: "网易云" })));
}
if (songs.length === 0) {
container.innerHTML = "未找到相关歌曲。";
return;
}
const items = await Promise.all(
songs.map(async song => {
const picUrl = await fetchSongPic(song.id);
return `
<div style="margin-bottom: 10px; padding: 10px; border: 1px solid #ddd;">
<img src="${picUrl}" alt="${song.name}" style="vertical-align: middle; margin-right: 10px; width: 50px; height: 50px;">
<strong>${song.name}</strong> - ${Array.isArray(song.artist) ? song.artist.join(", ") : song.artist} <br>
专辑: ${song.album || "无"} <br>
<button style="margin-top: 5px;" onclick="fetchLyrics(${song.id})">查看歌词</button>
</div>
`;
})
);
container.innerHTML = items.join("");
}
async function fetchSongPic(songId) {
try {
const response = await fetch(`${picApiUrl}${songId}&type=wy`);
if (!response.ok) {
throw new Error("请求失败,状态码: " + response.status);
}
const data = await response.json();
return data && data.code === 1 ? data.data : "https://via.placeholder.com/50"; // 占位图
} catch {
return "https://via.placeholder.com/50"; // 请求失败备用占位图
}
}
async function fetchLyrics(songId) {
const lyricsContainer = document.getElementById("lyrics-container");
lyricsContainer.innerText = "歌词加载中...";
try {
const response = await fetch(`${lyricsApiUrl}${songId}&type=wy`);
if (!response.ok) {
throw new Error("请求失败,状态码: " + response.status);
}
const data = await response.json();
displayLyrics(data);
} catch (error) {
lyricsContainer.innerText = "加载歌词失败:" + error.message;
}
}
function displayLyrics(data) {
const container = document.getElementById("lyrics-container");
if (data && data.code === 1 && data.data) {
const lyrics = data.data
.split("\\n")
.filter(line => line.trim() !== "")
.join("<br>");
container.innerHTML = `<pre>${lyrics}</pre>`;
} else {
container.innerText = data && data.msg ? data.msg : "未找到歌词内容。";
}
}
</script>
';
}
add_shortcode('fetch_lyrics', 'fetch_lyrics_shortcode');
接着,回到我们界面,调用函数
然后一切完成
しかし,我之前是尝试直接html注入的,但是失败了,没有办法请求。可能是WordPress对于界面JS有所限制吧,只能在特定的地方调用。这样也好,成熟的框架也就应当如此。