函数文档

print_footer_scripts()

💡 云策文档标注

概述

print_footer_scripts() 是 WordPress 核心函数,用于输出排队到页脚或延迟到 HTML head 之后的脚本。它返回已打印脚本的句柄数组,并涉及脚本连接和过滤机制。

关键要点

  • 函数返回 string[] 类型,表示已打印脚本的句柄数组。
  • 内部使用全局变量 $wp_scripts 和 $concatenate_scripts 来处理脚本连接设置。
  • 通过 apply_filters('print_footer_scripts', true) 钩子允许过滤是否打印页脚脚本。
  • 调用 WP_Scripts::do_footer_items() 处理页脚组项目,最后重置 WP_Scripts 状态。
  • 相关函数包括 script_concat_settings()、_print_scripts() 和 WP_Scripts 类方法。

代码示例

function print_footer_scripts() {
    global $wp_scripts, $concatenate_scripts;

    if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
        return array(); // No need to run if not instantiated.
    }
    script_concat_settings();
    $wp_scripts->do_concat = $concatenate_scripts;
    $wp_scripts->do_footer_items();

    if ( apply_filters( 'print_footer_scripts', true ) ) {
        _print_scripts();
    }

    $wp_scripts->reset();
    return $wp_scripts->done;
}

注意事项

  • 函数在 WordPress 2.8.0 版本引入,是脚本加载系统的一部分。
  • 如果 $wp_scripts 未实例化,函数直接返回空数组,避免不必要的运行。
  • 使用 print_footer_scripts 钩子可以自定义是否输出脚本,例如在特定条件下禁用。

📄 原文内容

Prints the scripts that were queued for the footer or too late for the HTML head.

Return

string[] Handles of the scripts that were printed.

Source

function print_footer_scripts() {
	global $wp_scripts, $concatenate_scripts;

	if ( ! ( $wp_scripts instanceof WP_Scripts ) ) {
		return array(); // No need to run if not instantiated.
	}
	script_concat_settings();
	$wp_scripts->do_concat = $concatenate_scripts;
	$wp_scripts->do_footer_items();

	/**
	 * Filters whether to print the footer scripts.
	 *
	 * @since 2.8.0
	 *
	 * @param bool $print Whether to print the footer scripts. Default true.
	 */
	if ( apply_filters( 'print_footer_scripts', true ) ) {
		_print_scripts();
	}

	$wp_scripts->reset();
	return $wp_scripts->done;
}

Hooks

apply_filters( ‘print_footer_scripts’, bool $print )

Filters whether to print the footer scripts.

Changelog

Version Description
2.8.0 Introduced.