1. functions.php– 主题功能的核心文件
完整代码示例
<?php
/**
* 主题功能文件 - 所有核心功能的集中地
*/
/**
* 1.1 主题初始化函数
* 这是最重要的钩子函数,在主题激活后立即执行
*/
function my_theme_setup() {
// 1.1.1 多语言支持
load_theme_textdomain('my-theme', get_template_directory() . '/languages');
// 1.1.2 自动添加Feed链接
add_theme_support('automatic-feed-links');
// 1.1.3 标题标签支持(WordPress自动管理标题)
add_theme_support('title-tag');
// 1.1.4 特色图片支持(文章缩略图)
add_theme_support('post-thumbnails');
// 1.1.5 自定义Logo
add_theme_support('custom-logo', array(
'height' => 100,
'width' => 400,
'flex-height' => true,
'flex-width' => true,
));
// 1.1.6 注册导航菜单
register_nav_menus(array(
'primary' => __('主导航菜单', 'my-theme'),
'footer' => __('页脚菜单', 'my-theme'),
'social' => __('社交媒体菜单', 'my-theme'),
));
// 1.1.7 HTML5标记支持
add_theme_support('html5', array(
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
'style',
'script',
));
// 1.1.8 自定义背景
add_theme_support('custom-background', array(
'default-color' => 'ffffff',
));
// 1.1.9 自定义页眉
add_theme_support('custom-header', array(
'width' => 1200,
'height' => 400,
'flex-height' => true,
));
// 1.1.10 定义图片尺寸
add_image_size('blog-thumbnail', 400, 300, true); // 博客缩略图
add_image_size('single-large', 1200, 600, true); // 文章大图
add_image_size('gallery-small', 200, 200, true); // 画廊小图
}
add_action('after_setup_theme', 'my_theme_setup');
/**
* 1.2 注册小工具区域
* 控制侧边栏、页脚等可拖拽内容区域
*/
function my_theme_widgets_init() {
// 主侧边栏
register_sidebar(array(
'name' => __('右侧边栏', 'my-theme'),
'id' => 'sidebar-1',
'description' => __('显示在页面右侧的小工具区域', 'my-theme'),
'before_widget' => '<section id="%1$s" class="widget %2$s">',
'after_widget' => '</section>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
));
// 页脚小工具区域(3列布局)
for ($i = 1; $i <= 3; $i++) {
register_sidebar(array(
'name' => sprintf(__('页脚区域 %d', 'my-theme'), $i),
'id' => 'footer-' . $i,
'description' => sprintf(__('页脚第 %d 列小工具区域', 'my-theme'), $i),
'before_widget' => '<div id="%1$s" class="footer-widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h4 class="footer-title">',
'after_title' => '</h4>',
));
}
}
add_action('widgets_init', 'my_theme_widgets_init');
/**
* 1.3 加载CSS和JavaScript文件
* 管理前端资源的核心函数
*/
function my_theme_scripts() {
// 1.3.1 加载主样式表
wp_enqueue_style('my-theme-style', get_stylesheet_uri(), array(), wp_get_theme()->get('Version'));
// 1.3.2 加载自定义样式
wp_enqueue_style('my-theme-main', get_template_directory_uri() . '/assets/css/main.css', array(), '1.0.0');
// 1.3.3 加载Google字体
wp_enqueue_style('my-theme-fonts', 'https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700&display=swap');
// 1.3.4 加载jQuery(WordPress自带)
wp_enqueue_script('jquery');
// 1.3.5 加载主JavaScript文件
wp_enqueue_script(
'my-theme-main-js',
get_template_directory_uri() . '/assets/js/main.js',
array('jquery'), // 依赖jQuery
'1.0.0',
true // 在页脚加载
);
// 1.3.6 移动端导航脚本
wp_enqueue_script(
'my-theme-navigation',
get_template_directory_uri() . '/assets/js/navigation.js',
array(),
'1.0.0',
true
);
// 1.3.7 评论回复脚本(仅单页)
if (is_singular() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
}
// 1.3.8 传递数据到JavaScript
wp_localize_script('my-theme-main-js', 'themeData', array(
'ajax_url' => admin_url('admin-ajax.php'),
'home_url' => home_url(),
'theme_url' => get_template_directory_uri(),
'is_mobile' => wp_is_mobile(),
'nonce' => wp_create_nonce('my_theme_nonce'),
));
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');
/**
* 1.4 自定义菜单输出
* 增强默认菜单功能
*/
class My_Theme_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$classes[] = 'menu-item-' . $item->ID;
// 添加自定义类
if ($item->current) {
$classes[] = 'active';
}
if ($item->current_item_parent) {
$classes[] = 'parent-active';
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args, $depth));
$class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';
$id = apply_filters('nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args, $depth);
$id = $id ? ' id="' . esc_attr($id) . '"' : '';
$output .= $indent . '<li' . $id . $class_names . '>';
$atts = array();
$atts['title'] = !empty($item->attr_title) ? $item->attr_title : '';
$atts['target'] = !empty($item->target) ? $item->target : '';
$atts['rel'] = !empty($item->xfn) ? $item->xfn : '';
$atts['href'] = !empty($item->url) ? $item->url : '';
$atts['class'] = 'nav-link';
$atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args, $depth);
$attributes = '';
foreach ($atts as $attr => $value) {
if (!empty($value)) {
$attributes .= ' ' . $attr . '="' . esc_attr($value) . '"';
}
}
$item_output = $args->before;
$item_output .= '<a' . $attributes . '>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</a>';
// 添加箭头图标(如果有子菜单)
if (in_array('menu-item-has-children', $classes)) {
$item_output .= '<span class="submenu-toggle"><i class="fas fa-chevron-down"></i></span>';
}
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
}
?>
2. header.php– 网站头部模板
完整代码示例
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo('charset'); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- SEO元标签 -->
<?php if (is_single() || is_page()) : ?>
<meta name="description" content="<?php echo wp_strip_all_tags(get_the_excerpt(), true); ?>">
<?php else : ?>
<meta name="description" content="<?php bloginfo('description'); ?>">
<?php endif; ?>
<!-- 结构化数据 -->
<?php if (is_single()) : ?>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "<?php the_title(); ?>",
"description": "<?php echo esc_attr(wp_strip_all_tags(get_the_excerpt())); ?>",
"image": "<?php echo esc_url(get_the_post_thumbnail_url(get_the_ID(), 'full')); ?>",
"datePublished": "<?php echo get_the_date('c'); ?>",
"author": {
"@type": "Person",
"name": "<?php the_author(); ?>"
},
"publisher": {
"@type": "Organization",
"name": "<?php bloginfo('name'); ?>",
"logo": {
"@type": "ImageObject",
"url": "<?php echo esc_url(get_custom_logo_url()); ?>"
}
}
}
</script>
<?php endif; ?>
<!-- 网站图标 -->
<link rel="icon" href="<?php echo esc_url(get_template_directory_uri()); ?>/assets/images/favicon.ico" type="image/x-icon">
<link rel="apple-touch-icon" href="<?php echo esc_url(get_template_directory_uri()); ?>/assets/images/apple-touch-icon.png">
<!-- RSS Feed -->
<link rel="alternate" type="application/rss+xml" title="<?php bloginfo('name'); ?> RSS Feed" href="<?php bloginfo('rss2_url'); ?>">
<link rel="alternate" type="application/atom+xml" title="<?php bloginfo('name'); ?> Atom Feed" href="<?php bloginfo('atom_url'); ?>">
<!-- 文章页的上一篇/下一篇链接 -->
<?php
if (is_single()) {
previous_post_link('<link rel="prev" href="%link">');
next_post_link('<link rel="next" href="%link">');
}
?>
<!-- 规范URL -->
<?php if (is_single() || is_page()) : ?>
<link rel="canonical" href="<?php the_permalink(); ?>">
<?php endif; ?>
<!-- Pingback -->
<link rel="pingback" href="<?php bloginfo('pingback_url'); ?>">
<!-- 核心函数:必须放在所有wp_head调用之前 -->
<?php wp_head(); ?>
</head>
<body <?php body_class(); ?>>
<?php wp_body_open(); ?>
<!-- 页面加载动画 -->
<div id="page-loader">
<div class="loader-spinner"></div>
</div>
<div id="page" class="site">
<!-- 跳过导航链接(无障碍访问) -->
<a class="skip-link screen-reader-text" href="#primary">
<?php _e('跳到主要内容', 'my-theme'); ?>
</a>
<!-- 顶部栏 -->
<header id="masthead" class="site-header" role="banner">
<div class="header-top">
<div class="container">
<!-- 顶部信息 -->
<div class="header-info">
<div class="contact-info">
<span class="contact-item">
<i class="fas fa-phone"></i>
<a href="tel:400-000-0000">400-000-0000</a>
</span>
<span class="contact-item">
<i class="fas fa-envelope"></i>
<a href="mailto:info@example.com">info@example.com</a>
</span>
</div>
<!-- 社交媒体 -->
<div class="social-links">
<a href="#" class="social-link"><i class="fab fa-weixin"></i></a>
<a href="#" class="social-link"><i class="fab fa-weibo"></i></a>
<a href="#" class="social-link"><i class="fab fa-qq"></i></a>
</div>
</div>
</div>
</div>
<!-- 主头部 -->
<div class="header-main">
<div class="container">
<div class="header-inner">
<!-- Logo区域 -->
<div class="site-branding">
<?php
if (has_custom_logo()) {
the_custom_logo();
} else {
if (is_front_page() && is_home()) {
?>
<h1 class="site-title">
<a href="<?php echo esc_url(home_url('/')); ?>" rel="home">
<?php bloginfo('name'); ?>
</a>
</h1>
<?php
} else {
?>
<p class="site-title">
<a href="<?php echo esc_url(home_url('/')); ?>" rel="home">
<?php bloginfo('name'); ?>
</a>
</p>
<?php
}
$description = get_bloginfo('description', 'display');
if ($description || is_customize_preview()) {
?>
<p class="site-description"><?php echo $description; ?></p>
<?php
}
}
?>
</div><!-- .site-branding -->
<!-- 主导航菜单 -->
<nav id="site-navigation" class="main-navigation" role="navigation" aria-label="<?php esc_attr_e('主菜单', 'my-theme'); ?>">
<button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">
<span class="hamburger"></span>
<span class="screen-reader-text"><?php _e('菜单', 'my-theme'); ?></span>
</button>
<?php
wp_nav_menu(array(
'theme_location' => 'primary',
'menu_id' => 'primary-menu',
'menu_class' => 'nav-menu',
'container' => 'div',
'container_class' => 'primary-menu-wrapper',
'depth' => 3, // 最多3级菜单
'fallback_cb' => false,
'walker' => new My_Theme_Walker_Nav_Menu(),
));
?>
</nav><!-- #site-navigation -->
<!-- 头部工具 -->
<div class="header-tools">
<!-- 搜索框 -->
<div class="header-search">
<button class="search-toggle" aria-expanded="false">
<i class="fas fa-search"></i>
<span class="screen-reader-text"><?php _e('搜索', 'my-theme'); ?></span>
</button>
<div class="search-form-wrapper">
<?php get_search_form(); ?>
</div>
</div>
<!-- 用户功能 -->
<?php if (is_user_logged_in()) : ?>
<div class="user-menu">
<a href="<?php echo esc_url(get_edit_profile_url()); ?>" class="user-link">
<i class="fas fa-user"></i>
</a>
</div>
<?php else : ?>
<div class="login-link">
<a href="<?php echo esc_url(wp_login_url()); ?>" class="btn-login">
<i class="fas fa-sign-in-alt"></i>
<span><?php _e('登录', 'my-theme'); ?></span>
</a>
</div>
<?php endif; ?>
</div><!-- .header-tools -->
</div><!-- .header-inner -->
</div><!-- .container -->
</div><!-- .header-main -->
<!-- 粘性头部 -->
<div id="sticky-header"></div>
</header><!-- #masthead -->
<!-- 页面标题区域 -->
<?php if (!is_front_page()) : ?>
<div class="page-header">
<div class="container">
<div class="page-header-inner">
<?php
if (is_home()) {
echo '<h1 class="page-title">' . get_the_title(get_option('page_for_posts')) . '</h1>';
} elseif (is_archive()) {
the_archive_title('<h1 class="page-title">', '</h1>');
the_archive_description('<div class="archive-description">', '</div>');
} elseif (is_search()) {
printf('<h1 class="page-title">%s "%s"</h1>',
__('搜索结果:', 'my-theme'),
get_search_query()
);
} elseif (is_404()) {
echo '<h1 class="page-title">' . __('页面未找到', 'my-theme') . '</h1>';
} elseif (is_singular()) {
the_title('<h1 class="page-title">', '</h1>');
}
?>
<!-- 面包屑导航 -->
<?php if (function_exists('yoast_breadcrumb')) : ?>
<?php yoast_breadcrumb('<nav class="breadcrumb" aria-label="breadcrumb">', '</nav>'); ?>
<?php else : ?>
<nav class="breadcrumb" aria-label="breadcrumb">
<a href="<?php echo home_url(); ?>"><?php _e('首页', 'my-theme'); ?></a>
<?php
if (is_category()) {
echo '<span class="separator">/</span>';
single_cat_title();
} elseif (is_single()) {
echo '<span class="separator">/</span>';
the_category(' <span class="separator">/</span> ');
echo '<span class="separator">/</span>';
the_title();
} elseif (is_page()) {
echo '<span class="separator">/</span>';
the_title();
} elseif (is_search()) {
echo '<span class="separator">/</span>';
printf(__('搜索结果: %s', 'my-theme'), get_search_query());
} elseif (is_404()) {
echo '<span class="separator">/</span>';
_e('404 页面未找到', 'my-theme');
}
?>
</nav>
<?php endif; ?>
</div><!-- .page-header-inner -->
</div><!-- .container -->
</div><!-- .page-header -->
<?php endif; ?>
<!-- 主内容区域 -->
<div id="content" class="site-content">
<div class="container">
<div class="content-wrapper">
3. index.php– 主循环模板
完整代码示例
<?php
/**
* 主模板文件
* 控制博客首页、归档页的显示
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<!-- 文章列表区域 -->
<div class="posts-container">
<?php
if (have_posts()) :
// 首页特殊显示
if (is_home() && !is_front_page()) {
?>
<header class="page-header">
<h1 class="page-title"><?php single_post_title(); ?></h1>
<?php
$description = get_the_archive_description();
if ($description) {
echo '<div class="archive-description">' . $description . '</div>';
}
?>
</header>
<?php
}
// 分类页描述
if (is_category()) {
$category_description = category_description();
if (!empty($category_description)) {
echo '<div class="category-description">' . $category_description . '</div>';
}
}
// 标签页描述
if (is_tag()) {
$tag_description = tag_description();
if (!empty($tag_description)) {
echo '<div class="tag-description">' . $tag_description . '</div>';
}
}
// 开始循环
?>
<div class="posts-grid">
<?php
$post_count = 0;
while (have_posts()) :
the_post();
$post_count++;
// 设置不同的文章类
$post_class = 'post-item';
if (0 === $post_count % 3) {
$post_class .= ' post-item-third';
}
if (has_post_thumbnail()) {
$post_class .= ' has-thumbnail';
}
?>
<article id="post-<?php the_ID(); ?>" <?php post_class($post_class); ?>>
<!-- 文章特色图片 -->
<?php if (has_post_thumbnail()) : ?>
<div class="post-thumbnail">
<a href="<?php the_permalink(); ?>" aria-hidden="true" tabindex="-1">
<?php
the_post_thumbnail('blog-thumbnail', array(
'alt' => the_title_attribute(array('echo' => false)),
'loading' => 'lazy',
'class' => 'post-thumbnail-img'
));
?>
</a>
<!-- 文章分类 -->
<?php
$categories = get_the_category();
if (!empty($categories)) {
echo '<a href="' . esc_url(get_category_link($categories[0]->term_id)) . '" class="post-category">' . esc_html($categories[0]->name) . '</a>';
}
?>
</div><!-- .post-thumbnail -->
<?php endif; ?>
<div class="post-content">
<!-- 文章元信息 -->
<div class="post-meta">
<!-- 作者 -->
<span class="post-author">
<i class="fas fa-user"></i>
<a href="<?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))); ?>">
<?php the_author(); ?>
</a>
</span>
<!-- 发布时间 -->
<span class="post-date">
<i class="fas fa-calendar-alt"></i>
<time datetime="<?php echo esc_attr(get_the_date('c')); ?>">
<?php echo esc_html(get_the_date()); ?>
</time>
</span>
<!-- 评论数 -->
<span class="post-comments">
<i class="fas fa-comment"></i>
<a href="<?php comments_link(); ?>">
<?php
printf(
_n('%s 条评论', '%s 条评论', get_comments_number(), 'my-theme'),
number_format_i18n(get_comments_number())
);
?>
</a>
</span>
<!-- 阅读量(需要插件支持) -->
<?php
$views = get_post_meta(get_the_ID(), 'post_views', true);
if ($views) {
echo '<span class="post-views"><i class="fas fa-eye"></i>' . intval($views) . '</span>';
}
?>
</div><!-- .post-meta -->
<!-- 文章标题 -->
<header class="post-header">
<?php
if (is_sticky() && is_home()) {
echo '<span class="sticky-post">' . __('置顶', 'my-theme') . '</span>';
}
?>
<h2 class="post-title">
<a href="<?php the_permalink(); ?>" rel="bookmark">
<?php the_title(); ?>
</a>
</h2>
</header><!-- .post-header -->
<!-- 文章摘要 -->
<div class="post-excerpt">
<?php
// 显示自定义摘要或自动摘要
if (has_excerpt()) {
echo wp_trim_words(get_the_excerpt(), 40, '...');
} else {
echo wp_trim_words(get_the_content(), 40, '...');
}
?>
</div><!-- .post-excerpt -->
<!-- 阅读更多按钮 -->
<div class="post-readmore">
<a href="<?php the_permalink(); ?>" class="readmore-link">
<?php _e('阅读更多', 'my-theme'); ?>
<i class="fas fa-arrow-right"></i>
</a>
</div>
<!-- 文章标签 -->
<?php
$tags = get_the_tags();
if ($tags) :
?>
<div class="post-tags">
<span class="tags-label"><?php _e('标签:', 'my-theme'); ?></span>
<ul class="tags-list">
<?php
foreach ($tags as $tag) {
echo '<li><a href="' . esc_url(get_tag_link($tag->term_id)) . '" rel="tag">' . esc_html($tag->name) . '</a></li>';
}
?>
</ul>
</div>
<?php endif; ?>
</div><!-- .post-content -->
</article><!-- #post-<?php the_ID(); ?> -->
<?php
// 插入广告
if ($post_count === 3) {
?>
<div class="post-ad">
<?php
if (is_active_sidebar('content-ad-1')) {
dynamic_sidebar('content-ad-1');
}
?>
</div>
<?php
}
endwhile;
?>
</div><!-- .posts-grid -->
<!-- 分页 -->
<div class="posts-pagination">
<?php
the_posts_pagination(array(
'mid_size' => 2,
'prev_text' => __('<i class="fas fa-chevron-left"></i> 上一页', 'my-theme'),
'next_text' => __('下一页 <i class="fas fa-chevron-right"></i>', 'my-theme'),
'screen_reader_text' => __('文章导航', 'my-theme'),
));
?>
</div>
<?php
else :
// 没有文章时的显示
?>
<div class="no-posts">
<div class="no-posts-content">
<i class="fas fa-file-alt no-posts-icon"></i>
<h2><?php _e('暂无内容', 'my-theme'); ?></h2>
<p><?php _e('抱歉,没有找到您要的内容。', 'my-theme'); ?></p>
<?php if (is_search()) : ?>
<p><?php _e('请尝试其他关键词搜索。', 'my-theme'); ?></p>
<div class="search-again">
<?php get_search_form(); ?>
</div>
<?php endif; ?>
<a href="<?php echo esc_url(home_url('/')); ?>" class="btn-home">
<i class="fas fa-home"></i>
<?php _e('返回首页', 'my-theme'); ?>
</a>
</div>
</div>
<?php endif; ?>
</div><!-- .posts-container -->
<!-- 侧边栏 -->
<?php
if (!is_404() && is_active_sidebar('sidebar-1')) {
get_sidebar();
}
?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
?>
关键功能解析
1. functions.php的核心作用:
- 主题初始化:
add_theme_support()启用核心功能 - 资源加载:
wp_enqueue_style()和wp_enqueue_script()管理CSS/JS - 菜单注册:
register_nav_menus()定义菜单位置 - 小工具:
register_sidebar()注册小工具区域 - 图片支持:
add_theme_support('post-thumbnails')启用特色图片 - 自定义菜单:创建
Walker_Nav_Menu类扩展菜单功能
2. header.php的关键功能:
- 文档类型声明:
<!DOCTYPE html>必须放在第一行 - 语言属性:
language_attributes()输出正确的语言代码 - 字符集:
bloginfo('charset')获取编码设置 - 响应式视图:viewport 设置
wp_head():WordPress核心功能,必须调用body_class():自动为body添加CSS类wp_body_open():WordPress 5.2+新增钩子- 菜单输出:
wp_nav_menu()输出导航菜单 - 面包屑导航:SEO友好的导航路径
- 结构化数据:Schema.org标记,提升SEO
3. index.php的循环逻辑:
get_header():包含头部模板have_posts():检查是否有文章the_post():循环中的文章设置the_ID():获取文章IDpost_class():为文章添加CSS类the_permalink():获取文章链接the_title():输出文章标题the_content() /the_excerpt():文章内容/摘要the_post_thumbnail():输出特色图片get_the_category():获取文章分类get_the_tags():获取文章标签get_the_author():获取作者get_the_date():获取日期comments_number():获取评论数the_posts_pagination():输出分页导航get_sidebar():包含侧边栏模板get_footer():包含页脚模板
最佳实践建议
- 使用子主题:所有修改应在子主题中进行
- 错误处理:使用
is_active_sidebar()检查小工具 - 转义输出:使用
esc_url()、esc_html()、esc_attr() - 性能优化:合理使用缩略图尺寸
- SEO友好:使用语义化HTML标记
- 无障碍访问:添加适当的ARIA属性
- 移动端优先:确保响应式设计
- 安全防护:验证和过滤所有用户输入
这三个文件构成了WordPress主题的核心骨架,理解它们的工作原理是开发自定义主题的基础。


湘公网安备43020002000238