钩子文档

wp_loaded

💡 云策文档标注

概述

wp_loaded 是一个 WordPress 动作钩子,在 WordPress 核心、所有插件和主题完全加载并实例化后触发。它位于 init 之后、admin_init 之前,适用于前端和管理端的初始化阶段。

关键要点

  • wp_loaded 钩子在 init 之后、admin_init 之前执行,用于处理加载完成后的自定义代码。
  • AJAX 请求应使用 wp-admin/admin-ajax.php,该文件可处理未登录用户的请求。
  • 钩子执行顺序:前端为 init -> widgets_init -> wp_loaded;管理端为 init -> widgets_init -> wp_loaded -> admin_menu -> admin_init。
  • 可通过 add_action('wp_loaded', 'function_name') 添加自定义函数,支持条件判断(如 !is_admin())以仅在前端运行。

代码示例

// 示例1:使用 wp_loaded 钩子压缩 HTML 输出
add_action('wp_loaded', 'my_minify_html');
function my_minify_html() {
    ob_start('html_compress');
}

function html_compress($html) {
    // 压缩 HTML 的代码
    return $html;
}

// 示例2:仅在前端加载函数
add_action('wp_loaded', 'my_front_end_function');
function my_front_end_function() {
    if (!is_admin()) {
        // 仅在前端执行的操作
    }
}

// 示例3:使用匿名函数(PHP 5.3+)
add_action('wp_loaded', function() {
    if (!is_admin()) {
        // 仅在前端执行的操作
    }
});

注意事项

  • wp_loaded 钩子自 WordPress 3.0.0 版本引入,确保兼容性。
  • 在编写代码时,注意区分前端和管理端逻辑,可使用 is_admin() 函数进行条件判断。
  • 匿名函数需要 PHP 5.3 或更高版本支持。

📄 原文内容

This hook is fired once WP, all plugins, and the theme are fully loaded and instantiated.

Description

Ajax requests should use wp-admin/admin-ajax.php. admin-ajax.php can handle requests for users not logged in.

More Information

AJAX requests should use wp-admin/admin-ajax.php. admin-ajax.php can handle requests for users not logged in.

The wp_loaded action fires after init but before admin_init.

Front-End: init -> widgets_init -> wp_loaded
Admin: init -> widgets_init -> wp_loaded -> admin_menu -> admin_init

Source

do_action( 'wp_loaded' );

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Migrate from Codex:

    Minify HTML codes when page is output

    add_action( 'wp_loaded','my_minify_html' );
    function my_minify_html() {
    	// Use html_compress($html) function to minify html codes.
    	ob_start('html_compress');
    }
    
    function html_compress( $html ) {
    	// Some minify codes here...
    	return $html;
    }

    If you only want to load a function only in the front end.

    // If u want to load a function only in the front end.
    add_action( 'wp_loaded', 'my_front_end_function');
    function my_front_end_function() {
        if ( !is_admin() ) { 
            // Only target the front end
            // Do what you need to do
        }
    }

    Same as above, but using anonymous function (PHP 5.3 or higher).

    add_action( 'wp_loaded', function () {
        if ( !is_admin() ) {
            // Only target the front end
            // Do what you need to do
        }
    });