
在使用 WordPress 建站时,很多人希望对主题进行个性化定制。但直接修改原主题会在更新时被覆盖,因此推荐使用「子主题」来安全地扩展和定制功能。
一、创建子主题
1. 创建子主题目录
进入你网站的 /wp-content/themes/ 目录,创建一个新的文件夹,例如:
/wp-content/themes/astra-child/
如果你的主主题是 Astra,那子主题名建议叫
astra-child。
2. 创建 style.css 文件
在子主题目录中创建一个 style.css 文件,添加如下内容:
/*
Theme Name: Astra 子主题
Template: astra
Description: 这是 Astra 的子主题
Version: 1.0
Author: 你的名字
*/
注意:
Theme Name是你子主题的名称Template必须是父主题的文件夹名(如 Astra 就是astra)
3. 创建 functions.php 文件
在子主题中创建 functions.php 文件,并加入以下代码以继承父主题样式:
<?php
// 加载父主题的样式
add_action('wp_enqueue_scripts', function () {
wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css');
});
二、在文章页显示特色图片
有时候主题不自动显示文章的特色图。你可以在子主题的 functions.php 中添加如下代码,让文章页顶部显示封面图:
add_filter('the_content', 'insert_featured_image_before_content');
function insert_featured_image_before_content($content) {
if (is_single() && has_post_thumbnail()) {
$featured_image = '<div class="post-featured-image">' . get_the_post_thumbnail(null, 'full') . '</div>';
$content = $featured_image . $content;
}
return $content;
}
可选美化 CSS,可在后台 → 外观 → 自定义 → 附加 CSS 添加:
.post-featured-image {
margin-bottom: 20px;
text-align: center;
}
.post-featured-image img {
max-width: 100%;
height: auto;
border-radius: 12px;
}
三、为代码块添加「复制」按钮功能
默认 WordPress 不带代码复制功能。你可以通过以下方式实现在每个 pre 标签上添加“复制”按钮。
在子主题 functions.php 中添加以下代码:
add_action('wp_footer', 'add_copy_code_assets');
function add_copy_code_assets() {
if (!is_admin()) {
echo '
<style>
.copy-btn {
position: absolute;
top: 8px;
right: 8px;
padding: 2px 8px;
font-size: 12px;
background: #0073aa;
color: #fff;
border: none;
border-radius: 3px;
cursor: pointer;
z-index: 10;
}
.code-block {
position: relative;
}
</style>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.querySelectorAll("pre").forEach(function(preTag) {
var btn = document.createElement("button");
btn.innerText = "复制";
btn.className = "copy-btn";
var wrapper = document.createElement("div");
wrapper.className = "code-block";
preTag.parentNode.insertBefore(wrapper, preTag);
wrapper.appendChild(preTag);
wrapper.appendChild(btn);
btn.addEventListener("click", function() {
var code = preTag.innerText;
navigator.clipboard.writeText(code).then(function() {
btn.innerText = "已复制";
setTimeout(() => btn.innerText = "复制", 1500);
});
});
});
});
</script>';
}
}
四、启用子主题
- 登录 WordPress 后台
- 前往【外观 → 主题】
- 找到刚刚创建的子主题(如“Astra 子主题”),点击启用
总结
通过子主题,我们实现了如下功能而不影响父主题更新:
- 安全继承父主题样式
- 自动在文章页顶部插入特色封面图
- 每段代码添加复制按钮,提升阅读体验
✅ 子主题是定制 WordPress 网站最安全、最推荐的方式。
如果你喜欢这类教程,欢迎收藏和关注本站,后续将分享更多 WordPress 实用技巧!