函数文档

wp_head()

💡 云策文档标注

概述

wp_head() 是一个 WordPress 核心函数,用于触发 wp_head 动作钩子,允许插件和主题在网页头部插入脚本、样式和元数据等关键元素。

关键要点

  • wp_head() 函数调用 do_action('wp_head') 来执行添加到 wp_head 钩子的回调函数。
  • 此函数应在主题的 header.php 文件中,紧邻 </head> 标签前调用,以确保正确加载头部资源。
  • wp_head 钩子自 WordPress 1.2.0 版本引入,广泛用于前端页面头部内容的动态生成。

代码示例

// 示例:添加 pingback URL 自动发现头部信息到单篇文章、页面或附件
if ( ! function_exists( 'wpdocs_pingbackurl_example' ) ) {
    function wpdocs_pingbackurl_example() {
        if ( is_singular() && pings_open() ) {
            echo '<link rel="pingback" href="' . esc_url( get_bloginfo( 'pingback_url' ) ) . '" />';
        }
    }
}
add_action( 'wp_head', 'wpdocs_pingbackurl_example' );

📄 原文内容

Fires the wp_head action.

Description

See ‘wp_head’.

Source

function wp_head() {
	/**
	 * Prints scripts or data in the head tag on the front end.
	 *
	 * @since 1.5.0
	 */
	do_action( 'wp_head' );
}

Hooks

do_action( ‘wp_head’ )

Prints scripts or data in the head tag on the front end.

Changelog

Version Description
1.2.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example. Plugins and WordPress core use this function to insert crucial elements into your document (e.g., scripts, styles, and meta tags). Always put wp_head() just before the closing tag of your theme (usually in header.php):

    <head>
    	<!-- First add the elements you need in <head>; then last, add: -->
    	
    </head>

  2. Skip to note 4 content

    Add a pingback url auto-discovery header for single posts, pages, or attachments.

    if ( ! function_exists( 'wpdocs_pingbackurl_example' ) ) {
    	function wpdocs_pingbackurl_example() {
    		if ( is_singular() && pings_open() ) {
    			echo '<link rel="pingback" href="' . esc_url( get_bloginfo( 'pingback_url' ) ) . '">';
    		}
    	}
    }
    add_action( 'wp_head', 'wpdocs_pingbackurl_example' );