钩子文档

parse_request

💡 云策文档标注

概述

parse_request 是一个 WordPress 动作钩子,在 WP 类的内置请求解析方法结束时触发,用于处理当前请求的所有查询变量。它仅影响主查询,不适用于 wp_query 等其他查询。

关键要点

  • 触发时机:在 WordPress 主 WP 类的请求解析方法结束时执行。
  • 参数:传递 $wp(WordPress 环境实例,引用传递)。
  • 作用范围:仅影响主查询,不影响 wp_query 等其他查询。
  • 类型:动作钩子,不期望返回值。
  • 引入版本:WordPress 2.1.0。

代码示例

add_action( 'parse_request', 'change_post_per_page_wpent' );

function change_post_per_page_wpent( $query ) {
    if (  'my_cpt' == $query->query_vars['post_type'] ) {
        $query->query_vars[ 'posts_per_page' ] = 3;
    }
    
    return $query;
}

注意事项

  • parse_request 是动作钩子,不期望返回值。
  • 钩子仅作用于主查询,使用 wp_query 的查询不受影响。

📄 原文内容

Fires once all query variables for the current request have been parsed.

Parameters

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

More Information

This action hook is executed at the end of WordPress’s built-in request parsing method in the main WP() class.

Attention! The parse_request hook affects only the main query and not queries made with wp_query, for example.

Source

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

Changelog

Version Description
2.1.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    Example migrated from Codex:

    add_action( 'parse_request', 'change_post_per_page_wpent' );
    
    function change_post_per_page_wpent( $query ) {
        if (  'my_cpt' == $query->query_vars['post_type'] ) {
            $query->query_vars[ 'posts_per_page' ] = 3;
        }
        
        return $query;
    }

  2. Skip to note 4 content

    Example: Search by post ID also in dashboard

    add_action( 'parse_request', function( $wp ) {
    	global $pagenow;
    
    	if ( ! is_admin() && 'edit.php' !== $pagenow ) {
    		return;
    	}
    
    	// Check query parameter [s] exist
    	if ( ! isset( $wp->query_vars['s'] ) ) {
    		return;
    	}
    
    	// Check numeric value
    	$post_id = absint( $wp->query_vars['s'] );
    	if ( ! $post_id ) {
    		return;
    	}
    
    	unset( $wp->query_vars['s'] );
    
    	$wp->query_vars['p'] = $post_id;
    } );