简明现代魔法 -> WordPress -> WordPress 的 wp() 函数分析
WordPress 的 wp() 函数分析
2010-03-22
wp() 函数位于 wp-includes/functions.php 中。其方法体如下:
/**
* Setup the WordPress query.
*
* @since 2.0.0
*
* @param string $query_vars Default WP_Query arguments.
*/
function wp( $query_vars = '' )
{
global $wp, $wp_query, $wp_the_query;
$wp->main( $query_vars );
if( !isset($wp_the_query) )
$wp_the_query = $wp_query;
}
这个函数用来设置 WordPress 查询,参数是 $query_vars,可选,默认的 WP_Query 参数。
该函数不返回任何值,它定义了三个全局变量:
- 使用全局变量:(对象)$wp
- 使用全局变量:(对象)$$wp_query
- 使用全局变量:(对象)$wp_the_query
wp() 函数执行了 WP 类的成员方法 main(),WP 类位于 wp-includes/classes.php 中。
main() 函数的代码如下:
/**
* Sets up all of the variables required by the WordPress environment.
*
* The action 'wp' has one parameter that references the WP object. It
* allows for accessing the properties and methods to further manipulate the
* object.
*
* @since 2.0.0
*
* @param string|array $query_args Passed to {@link parse_request()}
*/
function main($query_args = '')
{
$this->init(); // 初始化,获取当前用户信息
$this->parse_request($query_args); // 解析请求
$this->send_headers(); // 发送头信息
$this->query_posts(); // 查询日志
$this->handle_404(); // 操作404(URL地址不存在)
$this->register_globals(); // 注册全局变量
do_action_ref_array('wp', array(&$this));
}
比如 $this->parse_request(),它通过 $_SERVER['REQUEST_URI'] 和过滤得到字符串 'database-dict-for-wordpress-23/2008/02/25' 赋值给 $request_match,与存储在数据库中的 rewrite 规则集进行正则匹配,rewrite 规则集类似与下面这个样子,当然,比下面的多了很多。
[wp-feed.php$] => index.php?feed=feed
[wp-commentsrss2.php$] => index.php?feed=rss2&withcomments=1
[(about)/trackback/?$] => index.php?pagename=$matches[1]&tb=1
[page/?([0-9]{1,})/?$] => index.php?&paged=$matches[1]
[comments/(feed|rdf|rss|rss2|atom)/?$] => index.php?&feed=$matches[1]&withcomments=1
[search/(.+)/?$] => index.php?s=$matches[1]
[category/(.+?)/?$] => index.php?category_name=$matches[1]
[tag/(.+?)/?$] => index.php?tag=$matches[1]
我的请求与 '([^/]+)/([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})(/[0-9]+)?/?$' 这条匹配,所以我的请求被转化为 'name=database-dict-for-wordpress-23&year=2008&monthnum=02&day=25&page=',如果请求都没匹配上那就肯定404了。接着就是通过 $this->query_posts() 来查询日志信息了,查询不到那还是404。
把这些都整完了,回到 wp-blog-header.php,包含 wp-includes/template-loader.php 来加载模板并显示,日志显示日志,页面显示页面,404显示404,总之就是各神归位。
