函数文档

get_query_var()

💡 云策文档标注

概述

get_query_var() 函数用于检索 WP_Query 类中的查询变量值,支持自定义查询变量通过 'query_vars' 过滤器添加。它主要用于获取公共查询变量,如分页信息。

关键要点

  • 函数参数:$query_var(必需,查询变量键名),$default_value(可选,未设置时的默认值,默认为空字符串)。
  • 返回值:查询变量的内容,类型为 mixed。
  • 仅检索 WP_Query 识别的公共查询变量;自定义查询变量需通过 'query_vars' 过滤器添加。
  • 示例:获取当前分页号,静态首页需使用 'page' 变量而非 'paged'。

代码示例

// 添加自定义查询变量到 WP_Query
function themeslug_query_vars( $qvars ) {
    $qvars[] = 'custom_query_var';
    return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' );

// 获取当前分页号
$paged = get_query_var( 'paged', 1 );
echo 'Currently Browsing Page ', $paged;

// 静态首页获取分页号
$paged = get_query_var( 'page', 1 );
echo 'Currently Browsing Page ', $paged, ' on a static front page';

注意事项

  • get_query_var() 依赖于 WP_Query 类,通常在主查询循环内使用,但可在 $wp_query 初始化后外部调用。
  • 自定义查询变量必须通过 'query_vars' 过滤器注册才能被检索。
  • 在 WordPress 管理页面等非主查询场景中,可能需要使用 $_GET 替代。

📄 原文内容

Retrieves the value of a query variable in the WP_Query class.

Parameters

$query_varstringrequired
The variable key to retrieve.
$default_valuemixedoptional
Value to return if the query variable is not set.
Default empty string.

Return

mixed Contents of the query variable.

More Information

get_query_var() only retrieves public query variables that are recognized by WP_Query. This means that if you create your own custom URLs with their own query variables, get_query_var() will not retrieve them without some further work (see below).

Custom Query Vars

In order to be able to add and work with your own custom query vars that you append to URLs (eg: “http://mysite.com/some_page/?my_var=foo” – for example using add_query_arg()) you need to add them to the public query variables available to WP_Query. These are built up when WP_Query instantiates, but fortunately are passed through a filter ‘query_vars‘ before they are actually used to populate the $query_vars property of WP_Query.

So, to expose your new, custom query variable to WP_Query hook into the ‘query_vars‘ filter, add your query variable to the $vars array that is passed by the filter, and remember to return the array as the output of your filter function. See below:

function themeslug_query_vars( $qvars ) {
$qvars[] = 'custom_query_var';
return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' );

Examples

Getting current page pagination number

$paged = get_query_var( 'paged', 1 );
echo 'Currently Browsing Page ', $paged;

To get the current pagination number on a static front page (Page template) you have to use the ‘page’ query variable:

$paged = get_query_var( 'page', 1 );
echo 'Currently Browsing Page ', $paged, ' on a static front page';

Note: The query variable ‘page’ holds the pagenumber for a single paginated Post or Page that includes the Quicktag in the post content.