一、子主题(Child Theme)开发入门
步骤1:创建子主题
-
在
/wp-content/themes/下新建文件夹(如astra-child) -
创建必需文件:
-
style.css 头部注释:
/* Theme Name: Astra Child Template: astra */ -
functions.php 加载父主题样式:
add_action( 'wp_enqueue_scripts', 'astra_child_enqueue_styles' ); function astra_child_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); } [content_hide]
-
步骤2:覆盖父主题模板
-
复制父主题文件:
-
例如修改文章页 → 复制
/astra/page.php到子主题目录
-
-
修改代码:
-
删除侧边栏:找到
get_sidebar();并注释 -
添加自定义Class:在
<article>标签添加class="custom-article"
-
步骤3:添加自定义功能
在functions.php中添加钩子:
// 在文章底部添加版权声明 add_filter( 'the_content', 'astra_child_add_copyright' ); function astra_child_add_copyright( $content ) { if ( is_single() ) { $content .= '<div class="copyright">本文禁止转载</div>'; } return $content; }
二、主题核心文件解析
1. 模板层级(Template Hierarchy)
-
控制不同页面的显示逻辑
-
优先级示例:
single-post.php>single.php>singular.php>index.php
2. 常用函数
| 函数名 | 作用 | 示例代码 |
|---|---|---|
get_header() |
调用头部模板 | <?php get_header(); ?> |
the_title() |
输出文章标题 | <h1><?php the_title(); ?></h1> |
wp_nav_menu() |
输出导航菜单 | <?php wp_nav_menu(['theme_location' => 'primary']); ?> |
3. 自定义文章类型(CPT)
-
在
functions.php中注册:
add_action( 'init', 'create_project_post_type' ); function create_project_post_type() { register_post_type( 'project', array( 'labels' => array( 'name' => '项目案例' ), 'public' => true, 'has_archive' => true, 'supports' => array( 'title', 'editor', 'thumbnail' ) ) ); }
三、调试与优化
1. 启用调试模式
在wp-config.php中添加:
define( 'WP_DEBUG', true ); define( 'WP_DEBUG_LOG', true ); // 错误日志保存到/wp-content/debug.log define( 'WP_DEBUG_DISPLAY', false ); // 不直接显示错误
2. 性能优化技巧
-
脚本排队(Defer/Async):
function defer_parsing_of_js( $url ) { if ( is_user_logged_in() ) return $url; if ( FALSE === strpos( $url, '.js' ) ) return $url; return "$url' defer='defer"; } add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
-
数据库索引优化:
使用插件「WP-Optimize」清理修订版本和垃圾数据
四、实操任务
-
任务1:用Elementor创建一个包含条件逻辑的「活动报名表单」
-
要求:根据用户选择的票种显示不同价格
-
-
任务2:创建子主题并移除父主题的页脚版权信息
-
任务3:注册一个「团队」自定义文章类型,支持分类和特色图片
[/content_hide]
© 版权声明
a.本站所有文章,如无特殊说明或标注,均为本站原创发布。
b.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。
c.如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
b.任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。
c.如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
THE END

















暂无评论内容