本文介绍如何从零开始开发WordPress自定义主题,包含主题结构、模板文件和functions.php配置。

主题目录结构

wp-content/themes/mytheme/
├── style.css          # 主题信息
├── index.php         # 主模板
├── header.php        # 头部
├── footer.php        # 底部
├── sidebar.php       # 侧边栏
├── functions.php    # 功能函数
├── single.php       # 文章详情
├── page.php         # 页面模板
└── archive.php      # 列表模板

创建style.css

在主题目录创建style.css:

/*
Theme Name: My Custom Theme
Theme URI: https://example.com
Author: Your Name
Author URI: https://example.com
Description: 自定义WordPress主题
Version: 1.0.0
License: GNU General Public License v2+
*/

创建index.php

<?php get_header(); ?>
<main>
    <?php if (have_posts()) : while (have_posts()) : the_post(); ?>
        <article>
            <h2><?php the_title(); ?></h2>
            <div><?php the_content(); ?></div>
        </article>
    <?php endwhile; endif; ?>
</main>
<?php get_footer(); ?>

创建functions.php

<?php
// _enqueue样式和脚本
function my_theme_scripts() {
    wp_enqueue_style('main', get_stylesheet_uri());
    wp_enqueue_script('main', get_template_directory_uri() . '/js/main.js', array(), '1.0.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');

// 添加主题支持
function my_theme_setup() {
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('automatic-feed-links');

    register_nav_menus(array(
        'primary' => '主菜单',
        'footer' => '底部菜单',
    ));
}
add_action('after_setup_theme', 'my_theme_setup');
?>

常用模板标签

标签 作用
the_title() 文章标题
the_content() 文章内容
the_excerpt() 文章摘要
the_post_thumbnail() 特色图片
the_permalink() 文章链接
the_date() 发布日期

header.php和footer.php

创建header.php:

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>

创建footer.php:

    <?php wp_footer(); ?>
</body>
</html>

启用主题

将主题文件夹上传到 wp-content/themes/,然后在后台启用。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。