杰瑞科技汇

WordPress模板教程该怎么学?

WordPress 模板终极教程:从零开始打造你的专属主题

WordPress 主题(也就是我们常说的“模板”)本质上是一组文件,它们共同定义了你网站的外观和感觉,学习创建主题是掌握 WordPress 开发的核心技能。

WordPress模板教程该怎么学?-图1
(图片来源网络,侵删)

本教程将带你走过整个过程,我们将一起创建一个名为 MyAwesomeTheme 的简单但功能完整的响应式主题。

目录

  1. 第一部分:准备工作与环境搭建
    • 了解 WordPress 主题结构
    • 本地开发环境搭建
  2. 第二部分:主题基础与核心文件
    • 创建主题文件夹和 style.css
    • 创建 index.php 和首页
    • 创建 header.phpfooter.php (模板引入)
    • 创建 functions.php (主题功能核心)
  3. 第三部分:构建循环
    • 什么是 The Loop?
    • 使用 have_posts()the_post()
    • 显示文章标题、内容、摘要和特色图片
  4. 第四部分:创建页面模板
    • 单文章页面 (single.php)
    • 页面模板 (page.php)
    • 404 错误页面 (php)
  5. 第五部分:打造侧边栏和页脚
    • 创建侧边栏 (sidebar.php)
    • 使用 get_sidebar()
    • 创建页脚小工具区域
  6. 第六部分:模板层次结构与高级技巧
    • WordPress 模板层次结构详解
    • 创建自定义页面模板 (全宽模板)
    • 使用 get_template_part() 模块化开发
  7. 第七部分:响应式设计与主题选项
    • 引入 CSS 和 JavaScript
    • 使用媒体查询实现响应式布局
    • 创建简单的主题选项面板 (使用 WordPress 自定义 API)
  8. 第八部分:最终步骤与主题发布
    • 国际化准备 (__()_e())
    • 创建 screenshot.png
    • 主题打包与上传
    • 代码规范与推荐资源

第一部分:准备工作与环境搭建

了解 WordPress 主题结构

一个标准的 WordPress 主题文件夹通常包含以下文件:

  • style.css必须文件,主题的“身份证”,包含主题的元信息(名称、作者、描述等)。
  • index.php必须文件,博客首页的默认模板。
  • header.php:网站头部模板,包含 <head> 标签、Logo、主导航等。
  • footer.php:网站页脚模板,包含版权信息、脚本等。
  • functions.php:主题功能文件,用于添加主题支持、注册菜单、小工具等。
  • single.php:单篇文章页面模板。
  • page.php:单页面模板。
  • archive.php:存档页面模板(如分类、标签、日期归档)。
  • search.php:搜索结果页面模板。
  • php:404 错误页面模板。
  • screenshot.png:主题的预览图(推荐尺寸 1200x900 像素)。
  • comments.php:评论模板。
  • sidebar.php:侧边栏模板。

本地开发环境搭建

在开始之前,强烈建议你在本地计算机上搭建一个 WordPress 环境,这样你就可以在不影响线上网站的情况下自由地测试和开发。

推荐工具:

WordPress模板教程该怎么学?-图2
(图片来源网络,侵删)
  • Local by Flywheel (最简单,一键式安装)
  • XAMPPMAMP (经典组合,需要手动配置)
  • Docker (适合有经验的开发者)

安装完成后,创建一个新的 WordPress 网站站点。


第二部分:主题基础与核心文件

创建主题文件夹和 style.css

  1. 在你的 WordPress 安装目录下的 wp-content/themes/ 文件夹中,创建一个新文件夹,命名为 myawesometheme
  2. myawesometheme 文件夹中,创建一个名为 style.css 的文件,并填入以下内容:
/*
Theme Name: My Awesome Theme
Theme URI: https://example.com/myawesometheme
Author: Your Name
Author URI: https://example.com
Description: A simple and responsive WordPress theme for learning.
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Text Domain: myawesometheme
*/
/* 在这里添加你的 CSS 代码 */
body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
    color: #333;
}

说明:

  • Theme Name:主题的显示名称。
  • Text Domain:用于国际化的文本域,非常重要。

登录你的 WordPress 后台,进入“外观” -> “主题”,你应该能看到“My Awesome Theme”并可以激活它,激活后,你的网站会变得非常简陋,因为我们还没有创建其他文件。

创建 header.phpfooter.php

header.php:这是网站的头部。

WordPress模板教程该怎么学?-图3
(图片来源网络,侵删)

myawesometheme 文件夹中创建 header.php,并添加以下代码:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo( 'charset' ); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="profile" href="https://gmpg.org/xfn/11">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<div id="page" class="site">
    <a class="skip-link screen-reader-text" href="#primary"><?php esc_html_e( 'Skip to content', 'myawesometheme' ); ?></a>
    <header id="masthead" class="site-header">
        <div class="site-branding">
            <?php
            if ( has_custom_logo() ) :
                the_custom_logo();
            else :
                ?>
                <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>
                <p class="site-description"><?php bloginfo( 'description' ); ?></p>
            <?php endif; ?>
        </header><!-- #masthead -->
</div>

footer.php:这是网站的页脚。

创建 footer.php 文件:

    <footer id="colophon" class="site-footer">
        <div class="site-info">
            <a href="<?php echo esc_url( __( 'https://wordpress.org/', 'myawesometheme' ) ); ?>">
                <?php
                /* translators: %s: CMS name, i.e. WordPress. */
                printf( esc_html__( 'Proudly powered by %s', 'myawesometheme' ), 'WordPress' );
                ?>
            </a>
            <span class="sep"> | </span>
            <?php
            /* translators: 1: Theme name, 2: Theme author. */
            printf( esc_html__( 'Theme: %1$s by %2$s.', 'myawesometheme' ), 'My Awesome Theme', 'Your Name' );
            ?>
        </div><!-- .site-info -->
    </footer><!-- #colophon -->
    <?php wp_footer(); ?>
</body>
</html>

关键函数说明:

  • wp_head()必须,这个钩子会加载 WordPress 核心需要的 CSS 和 JavaScript 文件,以及插件添加的内容。
  • wp_footer()必须,这个钩子会加载页脚需要的脚本。
  • language_attributes(), bloginfo(), body_class(), esc_url(), esc_html_e():这些都是 WordPress 提供的、用于安全和国际化的重要函数。

创建 index.php 和首页

index.php 是博客首页的默认模板,它将引入头部和页脚,并在中间放置主要内容区域。

创建 index.php 文件:

<?php get_header(); ?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main">
        <?php
        if ( have_posts() ) :
            /* Start the Loop */
            while ( have_posts() ) : the_post();
                /*
                 * Include the Post-Format-specific template for the content.
                 * If you want to override this in a child theme, then include a file
                 * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                 */
                get_template_part( 'template-parts/content', get_post_format() );
            endwhile;
            the_posts_navigation();
        else :
            get_template_part( 'template-parts/content', 'none' );
        endif;
        ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>

关键函数说明:

  • get_header():引入 header.php 文件。
  • get_footer():引入 footer.php 文件。
  • get_sidebar():引入 sidebar.php 文件(我们稍后会创建)。

你的网站应该已经有一个基本的框架了,但中间内容区域还是空的,因为我们还没有创建 content.php 文件。

创建 functions.php

functions.php 是主题的“大脑”,用于注册各种功能。

创建 functions.php 文件:

<?php
/**
 * My Awesome Theme functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package My_Awesome_Theme
 */
if ( ! defined( 'MY_AWESOME_THEME_VERSION' ) ) {
    // @todo Replace version number
    define( 'MY_AWESOME_THEME_VERSION', '1.0.0' );
}
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into after_setup_theme, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
function myawesometheme_setup() {
    /*
     * Make theme available for translation.
     * Translations can be filed in the /languages/ directory.
     * If you're building a theme based on myawesometheme, use a find and replace
     * to change 'myawesometheme' to the name of your theme in all the template files.
     */
    load_theme_textdomain( 'myawesometheme', get_template_directory() . '/languages' );
    // Add default posts and comments RSS feed links to head.
    add_theme_support( 'automatic-feed-links' );
    /*
     * Let WordPress manage the document title.
     * By adding theme support, we declare that this theme does not use a
     * hard-coded <title> tag in the document head, and expect WordPress to
     * provide it for us.
     */
    add_theme_support( 'title-tag' );
    /*
     * Enable support for Post Thumbnails on posts and pages.
     *
     * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
     */
    add_theme_support( 'post-thumbnails' );
    // This theme uses wp_nav_menu() in one location.
    register_nav_menus(
        array(
            'menu-1' => esc_html__( 'Primary', 'myawesometheme' ),
        )
    );
    /*
     * Switch default core markup for search form, comment form, and comments
     * to output valid HTML5.
     */
    add_theme_support(
        'html5',
        array(
            'search-form',
            'comment-form',
            'comment-list',
            'gallery',
            'caption',
        )
    );
    // Set up the WordPress core custom background feature.
    add_theme_support(
        'custom-background',
        apply_filters(
            'myawesometheme_custom_background_args',
            array(
                'default-color' => 'ffffff',
                'default-image' => '',
            )
        )
    );
    // Add theme support for selective refresh for widgets.
    add_theme_support( 'customize-selective-refresh-widgets' );
    /**
     * Add support for core custom logo.
     *
     * @link https://codex.wordpress.org/Theme_Logo
     */
    add_theme_support(
        'custom-logo',
        array(
            'height'      => 250,
            'width'       => 250,
            'flex-width'  => true,
            'flex-height' => true,
        )
    );
}
add_action( 'after_setup_theme', 'myawesometheme_setup' );
/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 *
 * Priority 0 to make it available to lower priority callbacks.
 *
 * @global int $content_width
 */
function myawesometheme_content_width() {
    $GLOBALS['content_width'] = apply_filters( 'myawesometheme_content_width', 640 );
}
add_action( 'after_setup_theme', 'myawesometheme_content_width', 0 );
/**
 * Register widget area.
 *
 * @link https://developer.wordpress.org/themes/functionality/sidebars-widgets/
 */
function myawesometheme_widgets_init() {
    register_sidebar(
        array(
            'name'          => esc_html__( 'Sidebar', 'myawesometheme' ),
            'id'            => 'sidebar-1',
            'description'   => esc_html__( 'Add widgets here.', 'myawesometheme' ),
            'before_widget' => '<section id="%1$s" class="widget %2$s">',
            'after_widget'  => '</section>',
            'before_title'  => '<h2 class="widget-title">',
            'after_title'   => '</h2>',
        )
    );
}
add_action( 'widgets_init', 'myawesometheme_widgets_init' );
/**
 * Enqueue scripts and styles.
 */
function myawesometheme_scripts() {
    wp_enqueue_style( 'myawesometheme-style', get_stylesheet_uri(), array(), MY_AWESOME_THEME_VERSION );
    wp_enqueue_style( 'myawesometheme-fonts', 'https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap', array(), null );
    wp_enqueue_script( 'myawesometheme-navigation', get_template_directory_uri() . '/js/navigation.js', array(), MY_AWESOME_THEME_VERSION, true );
    if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
        wp_enqueue_script( 'comment-reply' );
    }
}
add_action( 'wp_enqueue_scripts', 'myawesometheme_scripts' );
/**
 * Implement the Custom Header feature.
 */
require get_template_directory() . '/inc/custom-header.php';
/**
 * Custom template tags for this theme.
 */
require get_template_directory() . '/inc/template-tags.php';
/**
 * Functions which enhance the theme by hooking into WordPress.
 */
require get_template_directory() . '/inc/template-functions.php';
/**
 * Customizer additions.
 */
require get_template_directory() . '/inc/customizer.php';
/**
 * Load Jetpack compatibility file.
 */
if ( defined( 'JETPACK__VERSION' ) ) {
    require get_template_directory() . '/inc/jetpack.php';
}

说明:

  • myawesometheme_setup():这是最重要的函数,我们在这里注册了 WordPress 的各种功能支持,如导航菜单、特色图片、自定义 Logo、HTML5 标记等。
  • myawesometheme_widgets_init():注册侧边栏小工具区域。
  • myawesometheme_scripts():用于加载 CSS 和 JavaScript 文件。wp_enqueue_stylewp_enqueue_script 是正确加载样式和脚本的推荐方式,可以避免冲突。

第三部分:构建循环

循环是 WordPress 的核心,它负责从数据库中查询文章并显示它们。

创建 template-parts/content.php

index.php 中使用了 get_template_part( 'template-parts/content', get_post_format() ),这意味着它会尝试加载 template-parts/content.php 文件,如果文章有特定的格式(如 aside, gallery),它会尝试加载 template-parts/content-aside.php 等,这种模块化的方式非常好。

myawesometheme 文件夹下创建 template-parts 文件夹,然后在其中创建 content.php 文件。

<?php
/**
 * Template part for displaying posts
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package My_Awesome_Theme
 */
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
    <header class="entry-header">
        <?php
        if ( is_singular() ) :
            the_title( '<h1 class="entry-title">', '</h1>' );
        else :
            the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );
        endif;
        if ( 'post' === get_post_type() ) :
            ?>
            <div class="entry-meta">
                <?php
                myawesometheme_posted_on();
                myawesometheme_posted_by();
                ?>
            </div><!-- .entry-meta -->
        <?php endif; ?>
    </header><!-- .entry-header -->
    <?php myawesometheme_post_thumbnail(); ?>
    <div class="entry-summary">
        <?php the_excerpt(); // 显示文章摘要 ?>
    </div><!-- .entry-summary -->
    <footer class="entry-footer">
        <?php myawesometheme_entry_footer(); ?>
    </footer><!-- .entry-footer -->
</article><!-- #post-<?php the_ID(); ?> -->

关键函数说明:

  • the_ID():输出当前文章的 ID。
  • post_class():为文章容器添加 CSS 类,方便样式定制。
  • is_singular():判断是否为单个文章或页面。
  • the_title():输出文章标题。
  • esc_url()get_permalink():安全地获取并输出文章的永久链接。
  • the_excerpt():输出文章的摘要(通常在首页和存档页显示)。
  • the_content():输出文章的完整内容(通常在单文章页面显示)。

创建 template-parts/content-none.php

如果没有任何文章,我们需要显示一条提示信息,在 template-parts 文件夹中创建 content-none.php

<?php
/**
 * Template part for displaying a message that posts cannot be found.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/
 *
 * @package My_Awesome_Theme
 */
?>
<section class="no-results not-found">
    <header class="page-header">
        <h1 class="page-title"><?php esc_html_e( 'Nothing Found', 'myawesometheme' ); ?></h1>
    </header><!-- .page-header -->
    <div class="page-content">
        <?php
        if ( is_home() && current_user_can( 'publish_posts' ) ) :
            printf(
                '<p>' . wp_kses(
                    /* translators: 1: Link to WP admin new post page. */
                    __( 'Ready to publish your first post? <a href="%1$s">Get started here</a>.', 'myawesometheme' ),
                    array(
                        'a' => array(
                            'href' => array(),
                        ),
                    )
                ) . '</p>',
                esc_url( admin_url( 'post-new.php' ) )
            );
        elseif ( is_search() ) :
            ?>
            <p><?php esc_html_e( 'Sorry, but nothing matched your search terms. Please try again with some different keywords.', 'myawesometheme' ); ?></p>
            <?php
            get_search_form();
        else :
            ?>
            <p><?php esc_html_e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'myawesometheme' ); ?></p>
            <?php
            get_search_form();
        endif;
        ?>
    </div><!-- .page-content -->
</section><!-- .no-results -->

回到你的网站首页,你应该能看到文章列表了!如果还没有,请确保你已经有发布的文章。


第四部分:创建页面模板

单文章页面 (single.php)

当用户点击一篇文章的标题时,WordPress 会寻找 single.php 来显示完整内容。

创建 single.php

<?php
/**
 * Template for displaying all single posts
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package My_Awesome_Theme
 */
get_header();
?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main">
        <?php
        while ( have_posts() ) :
            the_post();
            get_template_part( 'template-parts/content', 'single' );
            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;
        endwhile; // End of the loop.
        ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php
get_sidebar();
get_footer();

注意:

  • single.php 的循环和 index.php 类似,但它通常会调用 template-parts/content-single.php 来显示单文章的布局(可能包含作者信息、相关文章、评论等)。
  • comments_template():引入评论模板。

页面模板 (page.php)

page.php 用于显示 WordPress 的“页面”(Page),和“文章”(Post)是分开的。

创建 page.php,它和 single.php 的结构非常相似:

<?php
/**
 * Template for displaying all pages
 *
 * This is the template that displays all pages by default.
 * Please note that this is the WordPress construct of pages and that
 * other 'pages' on your WordPress site will use a different template.
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
 *
 * @package My_Awesome_Theme
 */
get_header();
?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main">
        <?php
        while ( have_posts() ) :
            the_post();
            get_template_part( 'template-parts/content', 'page' );
            // If comments are open or we have at least one comment, load up the comment template.
            if ( comments_open() || get_comments_number() ) :
                comments_template();
            endif;
        endwhile; // End of the loop.
        ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php
get_sidebar();
get_footer();

404 错误页面 (php)

当用户访问一个不存在的页面时,php 就会被显示。

创建 php

<?php
/**
 * Template for displaying 404 pages (not found)
 *
 * @link https://developer.wordpress.org/themes/basics/template-hierarchy/#404-not-found
 *
 * @package My_Awesome_Theme
 */
get_header();
?>
    <div id="primary" class="content-area">
        <main id="main" class="site-main">
            <section class="error-404 not-found">
                <header class="page-header">
                    <h1 class="page-title"><?php esc_html_e( 'Oops! That page can&rsquo;t be found.', 'myawesometheme' ); ?></h1>
                </header><!-- .page-header -->
                <div class="page-content">
                    <p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'myawesometheme' ); ?></p>
                    <?php
                    get_search_form();
                    the_widget( 'WP_Widget_Recent_Posts' );
                    ?>
                    <div class="widget widget_categories">
                        <h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'myawesometheme' ); ?></h2>
                        <ul>
                            <?php
                            wp_list_categories(
                                array(
                                    'orderby'    => 'count',
                                    'order'      => 'DESC',
                                    'show_count' => 1,
                                    'title_li'   => '',
                                    'number'     => 10,
                                )
                            );
                            ?>
                        </ul>
                    </div><!-- .widget -->
                    <?php
                    /* translators: 1: Smilie */
                    $archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'myawesometheme' ), convert_smilies( ':)' ) ) . '</p>';
                    the_widget( 'WP_Widget_Archives', 'dropdown=1&count=0&show_count=0', "after_title=<h2 class='widget-title'>" . esc_html__( 'Archives', 'myawesometheme' ) . '</h2>' );
                    the_widget( 'WP_Widget_Tag_Cloud' );
                    ?>
                </div><!-- .page-content -->
            </section><!-- .error-404 -->
        </main><!-- #main -->
    </div><!-- #primary -->
<?php
get_sidebar();
get_footer();

第五部分:打造侧边栏和页脚

创建 sidebar.php

myawesometheme 根目录创建 sidebar.php

<?php
/**
 * The sidebar containing the main widget area
 *
 * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials
 *
 * @package My_Awesome_Theme
 */
if ( ! is_active_sidebar( 'sidebar-1' ) ) {
    return;
}
?>
<aside id="secondary" class="widget-area">
    <?php dynamic_sidebar( 'sidebar-1' ); ?>
</aside><!-- #secondary -->

关键函数说明:

  • is_active_sidebar( 'sidebar-1' ):检查我们之前在 functions.php 中注册的 sidebar-1 是否有添加小工具。
  • dynamic_sidebar( 'sidebar-1' ):显示该侧边栏区域的小工具。

你可以在 WordPress 后台的“外观” -> “小工具”中,将一些小工具(如“文章分类”、“近期文章”)拖拽到“侧边栏”区域,它们就会显示在你的网站上了。


第六部分:模板层次结构与高级技巧

WordPress 模板层次结构

WordPress 有一套非常智能的模板加载规则,称为“模板层次结构”,当你访问一个页面时,WordPress 会按以下顺序寻找最合适的模板文件:

  • 首页
    • front-page.php (如果设置了“静态首页”)
    • home.php
    • index.php (最终回退)
  • 单篇文章
    • single-{post-type}.php (single-product.php 用于 WooCommerce 产品)
    • single.php
    • singular.php
    • index.php (最终回退)
  • 页面
    • custom-page-template.php (自定义页面模板)
    • page-{slug}.php (page-about.php)
    • page-{id}.php (page-7.php)
    • page.php
    • singular.php
    • index.php (最终回退)
  • 存档页面
    • archive-{post-type}.php (archive-product.php)
    • archive-{taxonomy}.php (archive-category.php)
    • archive.php
    • index.php (最终回退)
  • 搜索结果
    • search.php
    • index.php (最终回退)
  • 404 错误
    • php
    • index.php (最终回退)

利用这个结构:你可以创建更具体的模板来满足不同需求,如果你想为“产品”类型的文章创建一个完全不同的布局,你只需要创建一个 single-product.php 文件即可。

创建自定义页面模板

假设你想创建一个全宽的页面,没有侧边栏。

  1. myawesometheme 文件夹中创建一个新文件,命名为 page-fullwidth.php
  2. 在文件顶部添加一个“模板名称”注释:
<?php
/**
 * Template Name: Full Width Page
 * Template Post Type: page
 *
 * @package My_Awesome_Theme
 */
get_header();
?>
    <div id="primary" class="content-area full-width">
        <main id="main" class="site-main">
            <?php
            while ( have_posts() ) :
                the_post();
                get_template_part( 'template-parts/content', 'page' );
                // If comments are open or we have at least one comment, load up the comment template.
                if ( comments_open() || get_comments_number() ) :
                    comments_template();
                endif;
            endwhile; // End of the loop.
            ?>
        </main><!-- #main -->
    </div><!-- #primary -->
<?php
// 注意:这里我们不调用 get_sidebar()
get_footer();

去 WordPress 后台编辑任意一个页面,在“页面属性”框中,你可以在“模板”下拉菜单里看到“Full Width Page”选项,选择它并更新页面,这个页面就会以全宽形式显示。

使用 get_template_part() 进行模块化开发

get_template_part() 是一个强大的函数,用于引入可重用的模板片段,我们已经用它来引入 content.php

你还可以使用它来分离文章的不同部分,将文章元信息(作者、日期)抽离到 template-parts/post/meta.php


第七部分:响应式设计与主题选项

引入 CSS 和 JavaScript

我们已经在 functions.phpmyawesometheme_scripts 函数中设置了样式和脚本的加载,我们需要为我们的主题创建一个 CSS 文件。

myawesometheme 文件夹中创建一个 css 文件夹,并在其中创建 style.css(注意,不是根目录的那个)。

myawesometheme/css/style.css:

/* 基础布局 */
.site-header {
    background: #fff;
    border-bottom: 1px solid #eee;
    padding: 1rem 0;
}
.site-branding {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}
#primary {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem 20px;
}
/* 文章样式 */
.entry-header {
    margin-bottom: 1.5rem;
}
.entry-title {
    font-size: 2rem;
    margin-bottom: 0.5rem;
}
.entry-meta {
    font-size: 0.875rem;
    color: #777;
}
/* 侧边栏样式 */
#secondary {
    max-width: 1200px;
    margin: 0 auto;
    padding: 2rem 20px;
}
/* 全宽页面样式 */
.full-width #primary {
    max-width: 100%;
}
/* 响应式设计 */
@media screen and (max-width: 768px) {
    .site-branding, #primary, #secondary {
        padding-left: 15px;
        padding-right: 15px;
    }
    .entry-title {
        font-size: 1.5rem;
    }
}

创建简单的主题选项面板 (使用 WordPress 自定义 API)

我们将使用 WordPress 内置的“自定义”功能来添加一个简单的选项,比如修改网站背景色。

  1. functions.php 中添加自定义izer代码
// 在 functions.php 文件末尾添加以下代码
/**
 * Customizer additions.
 */
function myawesometheme_customize_register( $wp_customize ) {
    // 添加一个设置
    $wp_customize->add_setting(
        'myawesometheme_bg_color',
        array(
            'default'   => '#f4f4f4', // 默认颜色
            'transport' => 'refresh', // 刷新页面来查看变化
        )
    );
    // 添加一个控件
    $wp_customize->add_control(
        new WP_Customize_Color_Control(
            $wp_customize,
            'myawesometheme_bg_color_control',
            array(
                'label'    => __( 'Background Color', 'myawesometheme' ),
                'section'  => 'colors',
                'settings' => 'myawesometheme_bg_color',
            )
        )
    );
}
add_action( 'customize_register', 'myawesometheme_customize_register' );
/**
 * 将自定义设置输出到head标签中
 */
function myawesometheme_customizer_css() {
    ?>
    <style type="text/css">
        body {
            background-color: <?php echo get_theme_mod( 'myawesometheme_bg_color', '#f4f4f4' ); ?>;
        }
    </style>
    <?php
}
add_action( 'wp_head', 'myawesometheme_customizer_css' );
  1. 测试
    • 登录 WordPress 后台,进入“外观” -> “自定义”。
    • 你应该能看到一个“颜色”部分,里面有一个“背景颜色”选项。
    • 点击它,选择一个颜色,然后点击“发布”。
    • 你的网站背景色应该会立即改变。

第八部分:最终步骤与主题发布

国际化准备 (__()_e())

为了让你的主题可以被翻译成其他语言,你需要使用 WordPress 的国际化函数。

  • __('文本', 'textdomain'):返回翻译后的文本,但不直接输出。
  • _e('文本', 'textdomain'):直接输出翻译后的文本。

我们已经在前面的代码中使用了这些函数,esc_html_e( 'Skip to content', 'myawesometheme' )

创建 screenshot.png

在你的主题根目录 myawesometheme 中,创建一张名为 screenshot.png 的图片,尺寸建议为 1200x900 像素,内容应该是你主题的预览图,这样,当用户在“外观” -> “主题”页面时,就能看到你的主题截图。

主题打包与上传

  1. 将整个 myawesometheme 文件夹压缩成一个 ZIP 文件。
  2. 登录 WordPress 后台,进入“外观” -> “主题” -> “添加新”。
  3. 点击“上传主题”,然后选择你刚刚创建的 ZIP 文件。
  4. 上传成功后,激活你的主题。

代码规范与推荐资源

分享:
扫描分享到社交APP
上一篇
下一篇