为什么要开发自定义主题?
现有主题无法满足设计需求、需要深度定制功能、或者要将品牌视觉系统精确落地——这些场景都需要掌握WordPress主题开发。即使你不打算从零开发主题,理解主题结构也能让你更有效地使用和修改现有主题。
子主题(Child Theme)
直接修改主题文件的最大风险是:主题更新后修改全部丢失。创建子主题是正确的做法。
创建子主题只需两步:
1. 创建子主题目录:在 wp-content/themes/ 下新建文件夹,如 mytheme-child/
2. 创建 style.css,必须包含以下声明头:
/*
Theme Name: My Theme Child
Template: twentytwentyfour
Version: 1.0
*/
@import url('../twentytwentyfour/style.css');
3. 创建 functions.php 正确加载父主题样式:
add_action('wp_enqueue_scripts', function() {
wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
wp_enqueue_style('child-style', get_stylesheet_uri(), ['parent-style']);
});
WordPress模板层级
WordPress访问不同页面时,按照特定优先级查找模板文件。以文章页为例,查找顺序为:
single-{post-type}-{slug}.php → single-{post-type}.php → single.php → singular.php → index.php
其他常用模板:front-page.php(首页)、page.php(静态页面)、archive.php(归档页)、category.php(分类页)、404.php(404页面)、search.php(搜索结果)。
常用Action钩子
Action钩子允许你在特定时机执行自定义代码:
// 在head中插入自定义代码
add_action('wp_head', function() {
echo '';
});
// 在footer中加载自定义脚本
add_action('wp_footer', function() {
echo '';
});
// 文章保存时触发
add_action('save_post', function($post_id) {
// 自定义逻辑
});
常用Filter钩子
Filter钩子允许你修改WordPress的数据和输出:
// 修改文章摘要长度
add_filter('excerpt_length', fn() => 120);
// 修改文章摘要省略号
add_filter('excerpt_more', fn() => '...');
// 在文章内容末尾添加版权声明
add_filter('the_content', function($content) {
if (is_single()) {
$content .= '本文版权归作者所有,转载请注明出处。
';
}
return $content;
});
functions.php最佳实践
- 用
add_theme_support()声明主题支持的功能(如缩略图、HTML5) - 用
register_nav_menus()注册导航菜单位置 - 用
register_sidebar()注册侧边栏widget区域 - 将功能模块拆分到独立的include文件,保持functions.php整洁
- 自定义代码加命名空间前缀避免冲突,如
mytheme_