首先,你需要安装 WPCode插件;
然后,新建一个code snippet,名为:ShowPic
插入方式选:Auto Insert
运行在: Run Anywhere
然后把下面的代码贴到 代码框,保存并Enable这个代码片段。
/**
* 将图片直接插入到链接所在位置
*/
function insert_images_at_link_positions() {
// 只在单篇文章页面执行
if (!is_single()) {
return;
}
// 添加必要的CSS和JavaScript
?>
<style>
/* 图片容器样式 */
.inserted-image-container {
display: block;
width: 400px;
margin: 15px 0;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
padding: 10px;
transition: box-shadow 0.3s ease;
}
.inserted-image-container:hover {
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}
/* 图片样式 */
.inserted-image-container img {
width: 100%;
height: auto;
border-radius: 5px;
display: block;
}
/* 图片标题样式 */
.inserted-image-title {
font-size: 14px;
color: #333;
text-align: center;
padding: 8px 5px 2px;
line-height: 1.3;
}
/* 原始链接样式 */
.image-source-link {
display: block;
font-size: 12px;
color: #666;
text-align: center;
margin-top: 5px;
}
.image-source-link:hover {
color: #0073aa;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function() {
// 获取文章内容
const postContent = document.querySelector('.entry-content, .post-content, article');
if (!postContent) return;
// 查找所有图片链接 - 注意:我们需要使用数组来存储链接,因为当我们修改DOM时,NodeList会动态变化
const links = Array.from(postContent.querySelectorAll('a'));
// 遍历链接,寻找指向图片的链接
links.forEach(link => {
const href = link.getAttribute('href');
const linkText = link.textContent || '图片';
// 检查链接是否指向图片
if (href && href.match(/\.(jpeg|jpg|gif|png)($|\?)/i)) {
// 创建图片容器
const container = document.createElement('div');
container.className = 'inserted-image-container';
// 创建图片元素
const img = document.createElement('img');
img.src = href;
img.alt = linkText;
img.loading = 'lazy';
// 创建标题
const title = document.createElement('div');
title.className = 'inserted-image-title';
title.textContent = linkText;
// 创建原始链接信息(可选)
const sourceLink = document.createElement('a');
sourceLink.className = 'image-source-link';
sourceLink.href = href;
sourceLink.textContent = '查看原图';
sourceLink.target = '_blank';
// 添加到容器
container.appendChild(img);
container.appendChild(title);
container.appendChild(sourceLink);
// 在链接后面插入图片容器
link.parentNode.insertBefore(container, link.nextSibling);
// 为原始链接添加样式标记(可选)
link.classList.add('has-inserted-image');
}
});
});
</script>
<?php
}
// 在wp_head钩子上挂载我们的函数
add_action('wp_head', 'insert_images_at_link_positions');