`Functions.php` 文件既可用于经典主题、块主题和子主题。

functions.php 文件是添加 WordPress 主题独特功能的地方。它可以用于挂钩到 WordPress 的核心函数,使您的主题更加模块化、可扩展且实用。

什么是 functions.php?

functions.php 文件的行为像一个 WordPress 插件,为 WordPress 站点添加功能和功能。您可以使用它来调用 WordPress 函数并定义自己的函数。

The same result can be produced using either a plugin or functions.php. If you are creating new features that should be available no matter what the website looks like, it is best practice to put them in a plugin.

使用 WordPress 插件或使用 functions.php 各有优缺点。

WordPress 插件:

  • 需要特定的唯一标题文本;
  • 存储在 wp-content/plugins,通常在子目录中;
  • 仅在激活时页面加载时执行;
  • 适用于所有主题;以及
  • 应该具有单一目的——例如,提供搜索引擎优化功能或帮助备份。

同时,functions.php 文件:

  • 不需要唯一的标题文本;
  • 存储在 wp-content/themes 中的主题的子目录中;
  • 仅在活动的主题目录中执行;
  • 仅适用于该主题(如果更改了主题,则无法再使用这些功能);以及
  • 可以有许多用于不同目的的代码块。

每个主题都有自己的函数文件,但只有活动主题的 functions.php 中的代码实际上才会运行。如果您的主题已经有了一个 functions 文件,您可以向其添加代码。如果没有,您可以创建一个名为 functions.php 的纯文本文件添加到您的主题的目录中,如下所示。

子主题可以有自己的functions.php 文件。向子函数文件添加功能是修改父主题的一种无风险方式。这样,当更新父主题时,您不必担心新添加的函数会消失。

Although the child theme's functions.php is loaded by WordPress right before the parent theme's functions.php, it does not override it. The child theme's functions.php can be used to augment or replace the parent theme's functions. Similarly, functions.php is loaded after any plugin files have loaded.

使用 functions.php 您可以:

  • 使用 WordPress hooks。例如,通过the excerpt_length filter,您可以更改您的帖子摘要长度(默认值为 55 个单词)。
  • 使用add_theme_support()启用 WordPress 功能。例如,打开帖子缩略图、帖子格式和导航菜单。
  • 定义您希望在多个主题模板文件中重复使用的函数。

In WordPress, naming conflicts can occur when two or more functions, classes, or variables have the same name. This can cause errors or unexpected behavior in a WordPress site. It is the responsibility of both the theme developer and plugin developer to avoid naming conflicts in their respective code.

主题开发人员应确保其函数、类和变量具有不与 WordPress 核心或其他插件使用的名称冲突的唯一名称。他们还应该在其函数和类名前添加唯一标识符,例如主题名称或缩写,以最大限度地减少命名冲突的可能性。

示例

以下是您可以在 functions.php 文件中用于支持各种功能的许多示例。如果您选择将您的主题提交到 WordPress.org 主题目录,则这些示例中的每一个都允许在您的主题中使用。

主题设置

应包含若干主题功能在一个“setup”函数中,该函数在您激活主题时最初运行。如下所示,每个功能都可以添加到 functions.php 文件中以激活推荐的 WordPress 功能。

It's important to namespace your functions with your theme name. All examples below use myfirsttheme_ as their namespace, which should be customized based on your theme name.

To create this initial function, start a new function entitled myfirsttheme_setup(), like so:

if ( ! function_exists( 'myfirsttheme_setup' ) ) :
/**
 * Sets up theme defaults and registers support for various WordPress  
 * features.
 *
 * It is important to set up these functions before the init hook so
 * that none of these features are lost.
 *
 *  @since MyFirstTheme 1.0
 */
function myfirsttheme_setup() { ... }

注意:在上面的示例中,函数 myfirsttheme_setup 已启动但未关闭。请确保关闭您的函数。

自动馈送链接

Automatic feed links enables post and comment RSS feeds by default. These feeds will be displayed in <head> automatically. They can be called using add_theme_support() in classic themes. This feature is automatically enabled for block themes, and does not need to be included during theme setup.

add_theme_support( 'automatic-feed-links' );

导航菜单

In classic themes, custom navigation menus allow users to edit and customize menus in the Menus admin panel, giving users a drag-and-drop interface to edit the various menus in their theme.

You can set up multiple menus in functions.php. They can be added using register_nav_menus() and inserted into a theme using wp_nav_menu(), as discussed later in this handbook. If your theme will allow more than one menu, you should use an array. While some themes will not have custom navigation menus, it is recommended that you allow this feature for easy customization.

register_nav_menus( array(
    'primary'   => __( 'Primary Menu', 'myfirsttheme' ),
    'secondary' => __( 'Secondary Menu', 'myfirsttheme' )
) );

您定义的每个菜单都可以稍后使用 wp_nav_menu() 调用,并使用分配的名称(即 primary)作为 theme_location 参数。

In block themes, you use the navigation block instead.

加载文本域

Themes can be translated into multiple languages by making the strings in your theme available for translation. To do so, you must use load_theme_textdomain(). For more information on making your theme available for translation, read the internationalization section.

load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );

帖子缩略图

Post thumbnails and featured images allow your users to choose an image to represent their post. Your theme can decide how to display them, depending on its design. For example, you may choose to display a post thumbnail with each post in an archive view. Or, you may want to use a large featured image on your homepage. This feature is automatically enabled for block themes, and does not need to be included during theme setup.

add_theme_support( 'post-thumbnails' );

帖子格式

Post formats allow users to format their posts in different ways. This is useful for allowing bloggers to choose different formats and templates based on the content of the post. add_theme_support() is also used for Post Formats. This is recommended.

add_theme_support( 'post-formats',  array( 'aside', 'gallery', 'quote', 'image', 'video' ) );

Learn more about post formats.

块主题中的主题支持

In block themes, HTML5 markup as well as the following theme supports are enabled automatically:

add_theme_support( 'post-thumbnails' );
add_theme_support( 'responsive-embeds' );
add_theme_support( 'editor-styles' );
add_theme_support( 'automatic-feed-links' ); 

初始设置示例

Including all of the above features will give you a functions.php file like the one below. Code comments have been added for future clarity.

As shown at the bottom of this example, you must add the required add_action() statement to ensure the myfirsttheme_setup function is loaded.

if ( ! function_exists( 'myfirsttheme_setup' ) ) :
	/**
	 * Sets up theme defaults and registers support for various
	 * WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme
	 * hook, which runs before the init hook. The init hook is too late
	 * for some features, such as indicating support post thumbnails.
	 */
	function myfirsttheme_setup() {

    /**
	 * Make theme available for translation.
	 * Translations can be placed in the /languages/ directory.
	 */
		load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );

		/**
		 * Add default posts and comments RSS feed links to <head>.
		 */
		add_theme_support( 'automatic-feed-links' );

		/**
		 * Enable support for post thumbnails and featured images.
		 */
		add_theme_support( 'post-thumbnails' );

		/**
		 * Add support for two custom navigation menus.
		 */
		register_nav_menus( array(
			'primary'   => __( 'Primary Menu', 'myfirsttheme' ),
			'secondary' => __( 'Secondary Menu', 'myfirsttheme' ),
		) );

		/**
		 * Enable support for the following post formats:
		 * aside, gallery, quote, image, and video
		 */
		add_theme_support( 'post-formats', array( 'aside', 'gallery', 'quote', 'image', 'video' ) );
	}
endif; // myfirsttheme_setup
add_action( 'after_setup_theme', 'myfirsttheme_setup' );

内容宽度

In classic themes, a content width is added to your functions.php file to ensure that no content or assets break the container of the site. The content width sets the maximum allowed width for any content added to your site, including uploaded images. In the example below, the content area has a maximum width of 800 pixels. No content will be larger than that.

if ( ! isset ( $content_width) ) {
    $content_width = 800;
}

Themes that include a theme.json configuration file does not need to include the variable in functions.php. Instead, the content width is added to the layout setting in theme.json. You can learn more about using theme.json in the advanced section.

其他功能

There are other common features you can include in functions.php. Listed below are some of the most common features. Click through and learn more about each of these features.

  • Custom Headers -Classic themes
  • Sidebars (widget areas) -Classic themes
  • Custom Background -Classic themes
  • Title tag -Classic themes
  • Add Editor Styles
  • HTML5 -Classic themes

您的 functions.php 文件

If you choose to include all the functions listed above, this is what your functions.php might look like. It has been commented with references to above.

/**
 * MyFirstTheme's functions and definitions
 *
 * @package MyFirstTheme
 * @since MyFirstTheme 1.0
 */

/**
 * First, let's set the maximum content width based on the theme's
 * design and stylesheet.
 * This will limit the width of all uploaded images and embeds.
 */
if ( ! isset( $content_width ) ) {
	$content_width = 800; /* pixels */
}

if ( ! function_exists( 'myfirsttheme_setup' ) ) :

	/**
	 * Sets up theme defaults and registers support for various
	 * WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme
	 * hook, which runs before the init hook. The init hook is too late
	 * for some features, such as indicating support post thumbnails.
	 */
	function myfirsttheme_setup() {

		/**
		 * Make theme available for translation.
		 * Translations can be placed in the /languages/ directory.
		 */
		load_theme_textdomain( 'myfirsttheme', get_template_directory() . '/languages' );

		/**
		 * Add default posts and comments RSS feed links to <head>.
		 */
		add_theme_support( 'automatic-feed-links' );

		/**
		 * Enable support for post thumbnails and featured images.
		 */
		add_theme_support( 'post-thumbnails' );

		/**
		 * Add support for two custom navigation menus.
		 */
		register_nav_menus( array(
			'primary'   => __( 'Primary Menu', 'myfirsttheme' ),
			'secondary' => __( 'Secondary Menu', 'myfirsttheme' ),
		) );

		/**
		 * Enable support for the following post formats:
		 * aside, gallery, quote, image, and video
		 */
		add_theme_support( 'post-formats', array( 'aside', 'gallery', 'quote', 'image', 'video' ) );
	}
endif; // myfirsttheme_setup
add_action( 'after_setup_theme', 'myfirsttheme_setup' );