WordPress主题开发基础 – 从修改到创建

一、子主题(Child Theme)开发入门

步骤1:创建子主题

  1. /wp-content/themes/下新建文件夹(如astra-child

  2. 创建必需文件:

    • 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:覆盖父主题模板

  1. 复制父主题文件:

    • 例如修改文章页 → 复制/astra/page.php到子主题目录

  2. 修改代码:

    • 删除侧边栏:找到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)

  1. 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. 任务1:用Elementor创建一个包含条件逻辑的「活动报名表单」

    • 要求:根据用户选择的票种显示不同价格

  2. 任务2:创建子主题并移除父主题的页脚版权信息

  3. 任务3:注册一个「团队」自定义文章类型,支持分类和特色图片

[/content_hide]

© 版权声明
THE END
喜欢就支持一下吧
点赞14 分享
相关推荐
评论 抢沙发

请登录后发表评论

    暂无评论内容