Skip to content

4.6 编写 functions.php:主题功能支持

functions.php是WordPress主题的核心文件之一,它用于添加主题的功能支持,如菜单注册、小工具区域注册、主题支持等。编写一个规范的functions.php文件对于主题的正常运行至关重要。本章节将详细介绍如何编写functions.php文件。

基本结构

functions.php文件的基本结构应该包括以下部分:

  1. 主题支持:添加主题支持的功能,如自定义Logo、自定义背景等
  2. 菜单注册:注册导航菜单
  3. 小工具区域注册:注册侧边栏和其他小工具区域
  4. 脚本和样式引入:引入主题的JavaScript和CSS文件
  5. 自定义功能:添加主题的自定义功能

编写 functions.php

1. 主题支持

首先,我们需要添加主题支持的功能。

php
<?php
/**
 * Functions.php
 *
 * The main functions file for the theme.
 *
 * @package My_Custom_Theme
 */

/**
 * Sets up theme defaults and registers support for various WordPress features.
 */
function my_custom_theme_setup() {
    // 添加主题支持
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-logo');
    add_theme_support('custom-background');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    
    // 注册导航菜单
    register_nav_menus(array(
        'primary' => esc_html__('Primary Menu', 'my-custom-theme'),
        'footer' => esc_html__('Footer Menu', 'my-custom-theme'),
    ));
}
add_action('after_setup_theme', 'my_custom_theme_setup');

2. 脚本和样式引入

接下来,我们需要引入主题的JavaScript和CSS文件。

php
/**
 * Enqueues scripts and styles.
 */
function my_custom_theme_enqueue_scripts() {
    // 引入主题主样式
    wp_enqueue_style('my-custom-theme-style', get_stylesheet_uri());
    
    // 引入导航菜单脚本
    wp_enqueue_script('my-custom-theme-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), '1.0', true);
    
    // 引入主题主脚本
    wp_enqueue_script('my-custom-theme-script', get_template_directory_uri() . '/assets/js/script.js', array('jquery'), '1.0', true);
    
    // 引入评论脚本
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}
add_action('wp_enqueue_scripts', 'my_custom_theme_enqueue_scripts');

3. 小工具区域注册

然后,我们需要注册侧边栏和其他小工具区域。

php
/**
 * Registers widget areas.
 */
function my_custom_theme_widgets_init() {
    // 注册侧边栏
    register_sidebar(array(
        'name' => esc_html__('Sidebar', 'my-custom-theme'),
        'id' => 'sidebar-1',
        'description' => esc_html__('Add widgets here.', 'my-custom-theme'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
    
    // 注册页脚小工具区域
    register_sidebar(array(
        'name' => esc_html__('Footer Widget Area', 'my-custom-theme'),
        'id' => 'footer-1',
        'description' => esc_html__('Add widgets here.', 'my-custom-theme'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
}
add_action('widgets_init', 'my_custom_theme_widgets_init');

4. 自定义功能

最后,我们可以添加主题的自定义功能。

php
/**
 * Custom functions for the theme.
 */

/**
 * Custom excerpt length.
 */
function my_custom_theme_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'my_custom_theme_excerpt_length', 999);

/**
 * Custom excerpt more.
 */
function my_custom_theme_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'my_custom_theme_excerpt_more');

/**
 * Custom pagination.
 */
function my_custom_theme_pagination() {
    global $wp_query;
    
    $big = 999999999;
    
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages,
        'prev_text' => __('Previous', 'my-custom-theme'),
        'next_text' => __('Next', 'my-custom-theme'),
        'type' => 'list',
    ));
}

/**
 * Custom breadcrumbs.
 */
function my_custom_theme_breadcrumbs() {
    echo '<nav class="breadcrumbs">';
    echo '<a href="' . home_url() . '">' . __('Home', 'my-custom-theme') . '</a>';
    
    if (is_category() || is_single()) {
        echo ' &gt; ';
        the_category(', ');
        
        if (is_single()) {
            echo ' &gt; ';
            the_title();
        }
    } elseif (is_page()) {
        echo ' &gt; ';
        the_title();
    } elseif (is_search()) {
        echo ' &gt; ' . __('Search Results for', 'my-custom-theme') . ' "' . get_search_query() . '"';
    }
    
    echo '</nav>';
}

5. 完整的 functions.php 文件

将以上部分组合起来,我们得到完整的functions.php文件。

php
<?php
/**
 * Functions.php
 *
 * The main functions file for the theme.
 *
 * @package My_Custom_Theme
 */

/**
 * Sets up theme defaults and registers support for various WordPress features.
 */
function my_custom_theme_setup() {
    // 添加主题支持
    add_theme_support('title-tag');
    add_theme_support('post-thumbnails');
    add_theme_support('custom-logo');
    add_theme_support('custom-background');
    add_theme_support('html5', array(
        'search-form',
        'comment-form',
        'comment-list',
        'gallery',
        'caption',
    ));
    
    // 注册导航菜单
    register_nav_menus(array(
        'primary' => esc_html__('Primary Menu', 'my-custom-theme'),
        'footer' => esc_html__('Footer Menu', 'my-custom-theme'),
    ));
}
add_action('after_setup_theme', 'my_custom_theme_setup');

/**
 * Enqueues scripts and styles.
 */
function my_custom_theme_enqueue_scripts() {
    // 引入主题主样式
    wp_enqueue_style('my-custom-theme-style', get_stylesheet_uri());
    
    // 引入导航菜单脚本
    wp_enqueue_script('my-custom-theme-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), '1.0', true);
    
    // 引入主题主脚本
    wp_enqueue_script('my-custom-theme-script', get_template_directory_uri() . '/assets/js/script.js', array('jquery'), '1.0', true);
    
    // 引入评论脚本
    if (is_singular() && comments_open() && get_option('thread_comments')) {
        wp_enqueue_script('comment-reply');
    }
}
add_action('wp_enqueue_scripts', 'my_custom_theme_enqueue_scripts');

/**
 * Registers widget areas.
 */
function my_custom_theme_widgets_init() {
    // 注册侧边栏
    register_sidebar(array(
        'name' => esc_html__('Sidebar', 'my-custom-theme'),
        'id' => 'sidebar-1',
        'description' => esc_html__('Add widgets here.', 'my-custom-theme'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
    
    // 注册页脚小工具区域
    register_sidebar(array(
        'name' => esc_html__('Footer Widget Area', 'my-custom-theme'),
        'id' => 'footer-1',
        'description' => esc_html__('Add widgets here.', 'my-custom-theme'),
        'before_widget' => '<section id="%1$s" class="widget %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h3 class="widget-title">',
        'after_title' => '</h3>',
    ));
}
add_action('widgets_init', 'my_custom_theme_widgets_init');

/**
 * Custom functions for the theme.
 */

/**
 * Custom excerpt length.
 */
function my_custom_theme_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'my_custom_theme_excerpt_length', 999);

/**
 * Custom excerpt more.
 */
function my_custom_theme_excerpt_more($more) {
    return '...';
}
add_filter('excerpt_more', 'my_custom_theme_excerpt_more');

/**
 * Custom pagination.
 */
function my_custom_theme_pagination() {
    global $wp_query;
    
    $big = 999999999;
    
    echo paginate_links(array(
        'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
        'format' => '?paged=%#%',
        'current' => max(1, get_query_var('paged')),
        'total' => $wp_query->max_num_pages,
        'prev_text' => __('Previous', 'my-custom-theme'),
        'next_text' => __('Next', 'my-custom-theme'),
        'type' => 'list',
    ));
}

/**
 * Custom breadcrumbs.
 */
function my_custom_theme_breadcrumbs() {
    echo '<nav class="breadcrumbs">';
    echo '<a href="' . home_url() . '">' . __('Home', 'my-custom-theme') . '</a>';
    
    if (is_category() || is_single()) {
        echo ' &gt; ';
        the_category(', ');
        
        if (is_single()) {
            echo ' &gt; ';
            the_title();
        }
    } elseif (is_page()) {
        echo ' &gt; ';
        the_title();
    } elseif (is_search()) {
        echo ' &gt; ' . __('Search Results for', 'my-custom-theme') . ' "' . get_search_query() . '"';
    }
    
    echo '</nav>';
}

功能说明

1. 主题支持

add_theme_support()函数用于添加主题支持的功能,如:

  • title-tag:支持标题标签
  • post-thumbnails:支持特色图片
  • custom-logo:支持自定义Logo
  • custom-background:支持自定义背景
  • html5:支持HTML5标记

2. 菜单注册

register_nav_menus()函数用于注册导航菜单,我们可以在WordPress后台的"外观" > "菜单"中管理这些菜单。

3. 脚本和样式引入

wp_enqueue_style()函数用于引入CSS文件,wp_enqueue_script()函数用于引入JavaScript文件。

4. 小工具区域注册

register_sidebar()函数用于注册小工具区域,我们可以在WordPress后台的"外观" > "小工具"中管理这些小工具。

5. 自定义功能

我们可以添加各种自定义功能,如:

  • my_custom_theme_excerpt_length():自定义文章摘要长度
  • my_custom_theme_excerpt_more():自定义文章摘要结尾
  • my_custom_theme_pagination():自定义分页
  • my_custom_theme_breadcrumbs():自定义面包屑导航

最佳实践

  1. 结构清晰:保持functions.php文件的结构清晰,使用适当的缩进和注释
  2. 功能模块化:将不同的功能分成不同的函数,便于维护
  3. 性能优化:避免在functions.php中添加过多的功能,影响网站性能
  4. 安全性:确保代码安全,避免安全漏洞
  5. 兼容性:确保代码在不同版本的WordPress中都能正常工作
  6. 国际化:使用__()esc_html__()函数进行国际化

常见错误及解决方法

1. 语法错误

问题functions.php文件有语法错误,导致网站无法正常运行

解决方法:检查functions.php文件的语法,确保所有的括号和分号都正确

2. 功能不生效

问题:添加的功能不生效,可能是因为没有正确添加动作钩子

解决方法:确保使用正确的动作钩子,如:

php
add_action('after_setup_theme', 'my_custom_theme_setup');
add_action('wp_enqueue_scripts', 'my_custom_theme_enqueue_scripts');
add_action('widgets_init', 'my_custom_theme_widgets_init');

3. 脚本和样式不加载

问题:脚本和样式不加载,可能是因为路径不正确

解决方法:确保使用正确的路径,如:

php
wp_enqueue_style('my-custom-theme-style', get_stylesheet_uri());
wp_enqueue_script('my-custom-theme-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), '1.0', true);

4. 小工具区域不显示

问题:小工具区域不显示,可能是因为没有在模板文件中调用

解决方法:在模板文件中使用dynamic_sidebar()函数调用小工具区域:

php
<?php if (is_active_sidebar('sidebar-1')) : ?>
    <?php dynamic_sidebar('sidebar-1'); ?>
<?php endif; ?>

小结

functions.php文件是WordPress主题的重要组成部分,它用于添加主题的功能支持。通过本章节的学习,你应该:

  1. 了解functions.php文件的基本结构
  2. 掌握如何添加主题支持
  3. 掌握如何注册导航菜单和小工具区域
  4. 掌握如何引入脚本和样式
  5. 了解如何添加自定义功能
  6. 掌握functions.php文件的最佳实践
  7. 了解常见错误及解决方法

在后续的章节中,我们将详细介绍如何测试主题,以及如何构建完整的WordPress主题。

© 2026 编程马·菜鸟教程 版权所有