钩子文档

wp

💡 云策文档标注

概述

wp 是一个 WordPress 动作钩子,在 WordPress 环境设置完成后触发,允许开发者在查询之后、路由和处理之前执行高级过滤或验证操作。

关键要点

  • wp 钩子在 WordPress 环境设置完成后触发,参数 $wp 是当前 WordPress 环境实例的引用。
  • 此钩子在 WP::main() 方法中运行,位于 parse_request()、send_headers()、query_posts()、handle_404() 和 register_globals() 设置之前。
  • wp 钩子仅在前端页面或存在 WP_Query 的页面上工作,后台管理页面(如小工具页面)不会触发。

代码示例

function wpdocs_set_cookie() {
  // 使用 is_page 条件判断特定页面 ID
  if ( is_page( 126 ) ) {
    setcookie( "wpdocs-my-custom-cookie", "true", time() + ( YEAR_IN_SECONDS * 5 ), COOKIEPATH, COOKIE_DOMAIN, false ); 
  }
}

add_action( 'wp', 'wpdocs_set_cookie' );

注意事项

  • wp 钩子适用于前端页面或包含 WP_Query 的页面,后台管理页面不会调用此钩子。

📄 原文内容

Fires once the WordPress environment has been set up.

Parameters

$wpWP
Current WordPress environment instance (passed by reference).

More Information

The $wp object is passed to the hooked function as a reference (no return is necessary).

This hook is one effective place to perform any high-level filtering or validation, following queries, but before WordPress does any routing, processing, or handling. It is run in the main() WP method in which the $query_args are passed to parse_request(), as well as when send_headers() , query_posts()handle_404(), and register_globals() are setup.

Source

do_action_ref_array( 'wp', array( &$this ) );

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    This action will allow us to set a cookie in the headers but still have access to the WP class object. This example will show you how to set a cookie if you are on a specific page ID.

    function wpdocs_set_cookie() {
      // using is_page conditional for specific page ID
      if ( is_page( 126 ) ) {
        setcookie( "wpdocs-my-custom-cookie", "true", time() + ( YEAR_IN_SECONDS * 5 ), COOKIEPATH, COOKIE_DOMAIN, false ); 
      }
    }
    
    add_action( 'wp', 'wpdocs_set_cookie' );