6

オブジェクトを使用して新しいクエリ関数を作成しようとしていWP_Queryます。

新しいテンプレートファイルを作成し、次のように配置しました。

        $query_args = array(
            'post_type' => 'page',
            'post_parent=41',
        );

        // The Featured Posts query.
        $results = new WP_Query($query_args);

しかし、どの引数を使用しても、クエリは変更されません。クエリはすでに初期化されているように見え、新しいクエリを作成しWP_Queryても既存のクエリには影響しません。

私のコードの前に呼び出された唯一のワードプレス関数は、またはget_header()への呼び出しを含まないものです。WP_Queryquery_posts

次の行を入力して、実際のSQLクエリが何であるかを確認します。

echo $GLOBALS['wp_query']->request;

実際のSQLクエリは次のとおりです。

SELECT wp_posts.* FROM wp_posts WHERE 1=1 AND (wp_posts.ID = '14') AND wp_posts.post_type = 'page' ORDER BY wp_posts.post_date DESC

を変更しても、このクエリは変更されません$query_args

グローバル変数$wp_queryがいつ初期化されるのか、そして自分のクエリを使用するにはどうすればよいのでしょうか?

4

2 に答える 2

19

You are creating a new WP_Query object and saving it to $results. That is where the results of your query will be, not in $GLOBALS['wp_query']. Of course it doesn't overwrite $wp_query. They are different things. Try var_dump($results) instead.

You can overwrite $wp_query by creating a new WP_Query object like so: $wp_query = new WP_Query($query_args);. But that isn't efficient. You run two queries when you only need one. The better way to do it is to hook into pre_get_posts. Something like:

function alter_query_so_15250127($qry) {
   if ( $qry->is_main_query() && is_page('featured-posts-page') ) {
     $qry->set('post_type','page');
     $qry->set('post_parent',41);
   }
}
add_action('pre_get_posts','alter_query_so_15250127');

The if conditional is very important. You need to use that line to make sure the filter fires only on the page(s) you want it to fire on. Your question does not have enough detail for me to work out the precise conditions.

于 2013-03-06T14:54:37.777 に答える
8

http://codex.wordpress.org/Function_Reference/query_postsに投稿されている次の図を見てください。 ここに画像の説明を入力

于 2013-10-04T19:43:17.173 に答える