仕事でWordPressを使用する機会が多くなってきました。 しばらく触っていなかったので、復習をかねてWordPressがリクエストを処理するフローをまとめたいと思います。
WordPressはリクエストを、フロントコントローラーindex.phpで受けて、wp-blog-header.phpを呼び出します。
wp-blog-header.phpのソースコードを記載します。
<?php
if ( ! isset( $wp_did_header ) ) {
$wp_did_header = true;
// Load the WordPress library.
require_once( dirname( __FILE__ ) . '/wp-load.php' ); // 著者注 --- (1)
// Set up the WordPress query.
wp(); // 著者注 --- (2)
// Load the theme template.
require_once( ABSPATH . WPINC . '/template-loader.php' ); // 著者注 --- (3)
}
wp-blog-header.phpの(1)〜(3)が、WordPressがリクエストを処理する流れを表しています。
(1)〜(3)を順番に見ていきます。
wp-load.phpは、WordPressの初期化処理を実行します。
内部でwp-config.phpを読み込みます。さらにwp-config.phpは、wp-settings.phpを読み込みます。
wp-settings.phpは初期化処理を実行されます。
具体的には、以下のような処理を実行します。
wp-includes/**)wp_the_query = wp_query、wp_rwrite、wpなど)を作成(例 $GLOBALS['wp_the_query'] = new WP_Query())functions.phpを読み込み(functions.phpが読み込まれた直後に、after_set_upアクションを実行)initアクションを実行wp-loadアクションを実行wp関数は、パーマリンクからWordPressクエリを取得して、SQLを実行し投稿(WP_Postの配列)をメインクエリ(WP_Queryのインスタンスであるグローバル変数wp_query)のpostsプロパティに格納します。
発行したクエリ情報は、WP_Query::query_varsに格納されています。
(リライトルールも参照)
wp関数は、WP::main()を呼び出します。
WP::main()の処理は以下になります。
// 著者注 コメント等は削除
class WP {
// ...
public function main( $query_args = '' ) {
$this->init();
$this->parse_request( $query_args ); // 著者注 --- (a)
$this->send_headers();
$this->query_posts(); // 著者注 --- (b)
$this->handle_404();
$this->register_globals();
do_action_ref_array( 'wp', array( &$this ) );
}
// ...
}
https://github.com/s-hiroshi/note/edit/master/wordpress/query-loop.html
リクエストをパースして、WordPressクエリ変数(query vars)を、WP_Query::query_varsへ設定します。
WP::query_post()は、WP_Query::get_post()を呼び出します。
WP_Query::get_post()は、WP_Query::query_varsからSQLを作成・実行して、結果(WP_Postの配列)をメインクエリWP_Queryのpostsプロパティに格納します。
template-loader.phpは、メインクエリに応じてテンプレートを選択。
クエリタイプ(is_page, is_single, is_categoryなど)を判別可能な最初のアクションは、parse_query。
WP_Query::get_post()は、WP_Query::parse_query()をコールします。
WP_Query::parse_query()は、クエリタイプをセットします。
class WP_Query {
// ...
// 著者注 コメント等削除
public function get_posts() {
global $wpdb;
$this->parse_query(); // --- 著者注 parse_queryメソッドのなかにある parse_queryアクションが投稿クエリタイプを判別可能な最初のアクション
do_action_ref_array( 'pre_get_posts', array( &$this ) ); // 著者注 --- pre_get_postアクション内では投稿クエリタイプを判別可能
// ...
}
//...
}