]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/query.php
WordPress 4.1
[autoinstalls/wordpress.git] / wp-includes / query.php
1 <?php
2 /**
3  * WordPress Query API
4  *
5  * The query API attempts to get which part of WordPress the user is on. It
6  * also provides functionality for getting URL query information.
7  *
8  * @link http://codex.wordpress.org/The_Loop More information on The Loop.
9  *
10  * @package WordPress
11  * @subpackage Query
12  */
13
14 /**
15  * Retrieve variable in the WP_Query class.
16  *
17  * @see WP_Query::get()
18  * @since 1.5.0
19  * @uses $wp_query
20  *
21  * @param string $var       The variable key to retrieve.
22  * @param mixed  $default   Value to return if the query variable is not set. Default ''.
23  * @return mixed
24  */
25 function get_query_var( $var, $default = '' ) {
26         global $wp_query;
27
28         return $wp_query->get( $var, $default );
29 }
30
31 /**
32  * Retrieve the currently-queried object. Wrapper for $wp_query->get_queried_object()
33  *
34  * @uses WP_Query::get_queried_object
35  *
36  * @since 3.1.0
37  * @access public
38  *
39  * @return object
40  */
41 function get_queried_object() {
42         global $wp_query;
43         return $wp_query->get_queried_object();
44 }
45
46 /**
47  * Retrieve ID of the current queried object. Wrapper for $wp_query->get_queried_object_id()
48  *
49  * @uses WP_Query::get_queried_object_id()
50  *
51  * @since 3.1.0
52  * @access public
53  *
54  * @return int
55  */
56 function get_queried_object_id() {
57         global $wp_query;
58         return $wp_query->get_queried_object_id();
59 }
60
61 /**
62  * Set query variable.
63  *
64  * @see WP_Query::set()
65  * @since 2.2.0
66  * @uses $wp_query
67  *
68  * @param string $var Query variable key.
69  * @param mixed $value
70  * @return null
71  */
72 function set_query_var($var, $value) {
73         global $wp_query;
74
75         return $wp_query->set($var, $value);
76 }
77
78 /**
79  * Set up The Loop with query parameters.
80  *
81  * This will override the current WordPress Loop and shouldn't be used more than
82  * once. This must not be used within the WordPress Loop.
83  *
84  * @since 1.5.0
85  * @uses $wp_query
86  *
87  * @param string $query
88  * @return array List of posts
89  */
90 function query_posts($query) {
91         $GLOBALS['wp_query'] = new WP_Query();
92         return $GLOBALS['wp_query']->query($query);
93 }
94
95 /**
96  * Destroy the previous query and set up a new query.
97  *
98  * This should be used after {@link query_posts()} and before another {@link
99  * query_posts()}. This will remove obscure bugs that occur when the previous
100  * wp_query object is not destroyed properly before another is set up.
101  *
102  * @since 2.3.0
103  * @uses $wp_query
104  */
105 function wp_reset_query() {
106         $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
107         wp_reset_postdata();
108 }
109
110 /**
111  * After looping through a separate query, this function restores
112  * the $post global to the current post in the main query.
113  *
114  * @since 3.0.0
115  * @uses $wp_query
116  */
117 function wp_reset_postdata() {
118         global $wp_query;
119
120         if ( isset( $wp_query ) ) {
121                 $wp_query->reset_postdata();
122         }
123 }
124
125 /*
126  * Query type checks.
127  */
128
129 /**
130  * Is the query for an existing archive page?
131  *
132  * Month, Year, Category, Author, Post Type archive...
133  *
134  * @see WP_Query::is_archive()
135  * @since 1.5.0
136  * @uses $wp_query
137  *
138  * @return bool
139  */
140 function is_archive() {
141         global $wp_query;
142
143         if ( ! isset( $wp_query ) ) {
144                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
145                 return false;
146         }
147
148         return $wp_query->is_archive();
149 }
150
151 /**
152  * Is the query for an existing post type archive page?
153  *
154  * @see WP_Query::is_post_type_archive()
155  * @since 3.1.0
156  * @uses $wp_query
157  *
158  * @param mixed $post_types Optional. Post type or array of posts types to check against.
159  * @return bool
160  */
161 function is_post_type_archive( $post_types = '' ) {
162         global $wp_query;
163
164         if ( ! isset( $wp_query ) ) {
165                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
166                 return false;
167         }
168
169         return $wp_query->is_post_type_archive( $post_types );
170 }
171
172 /**
173  * Is the query for an existing attachment page?
174  *
175  * @see WP_Query::is_attachment()
176  * @since 2.0.0
177  * @uses $wp_query
178  *
179  * @param int|string|array|object $attachment Attachment ID, title, slug, or array of such.
180  * @return bool
181  */
182 function is_attachment( $attachment = '' ) {
183         global $wp_query;
184
185         if ( ! isset( $wp_query ) ) {
186                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
187                 return false;
188         }
189
190         return $wp_query->is_attachment( $attachment );
191 }
192
193 /**
194  * Is the query for an existing author archive page?
195  *
196  * If the $author parameter is specified, this function will additionally
197  * check if the query is for one of the authors specified.
198  *
199  * @see WP_Query::is_author()
200  * @since 1.5.0
201  * @uses $wp_query
202  *
203  * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
204  * @return bool
205  */
206 function is_author( $author = '' ) {
207         global $wp_query;
208
209         if ( ! isset( $wp_query ) ) {
210                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
211                 return false;
212         }
213
214         return $wp_query->is_author( $author );
215 }
216
217 /**
218  * Is the query for an existing category archive page?
219  *
220  * If the $category parameter is specified, this function will additionally
221  * check if the query is for one of the categories specified.
222  *
223  * @see WP_Query::is_category()
224  * @since 1.5.0
225  * @uses $wp_query
226  *
227  * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
228  * @return bool
229  */
230 function is_category( $category = '' ) {
231         global $wp_query;
232
233         if ( ! isset( $wp_query ) ) {
234                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
235                 return false;
236         }
237
238         return $wp_query->is_category( $category );
239 }
240
241 /**
242  * Is the query for an existing tag archive page?
243  *
244  * If the $tag parameter is specified, this function will additionally
245  * check if the query is for one of the tags specified.
246  *
247  * @see WP_Query::is_tag()
248  * @since 2.3.0
249  * @uses $wp_query
250  *
251  * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
252  * @return bool
253  */
254 function is_tag( $tag = '' ) {
255         global $wp_query;
256
257         if ( ! isset( $wp_query ) ) {
258                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
259                 return false;
260         }
261
262         return $wp_query->is_tag( $tag );
263 }
264
265 /**
266  * Is the query for an existing taxonomy archive page?
267  *
268  * If the $taxonomy parameter is specified, this function will additionally
269  * check if the query is for that specific $taxonomy.
270  *
271  * If the $term parameter is specified in addition to the $taxonomy parameter,
272  * this function will additionally check if the query is for one of the terms
273  * specified.
274  *
275  * @see WP_Query::is_tax()
276  * @since 2.5.0
277  * @uses $wp_query
278  *
279  * @param string|array $taxonomy Optional. Taxonomy slug or slugs.
280  * @param int|string|array $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
281  * @return bool
282  */
283 function is_tax( $taxonomy = '', $term = '' ) {
284         global $wp_query;
285
286         if ( ! isset( $wp_query ) ) {
287                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
288                 return false;
289         }
290
291         return $wp_query->is_tax( $taxonomy, $term );
292 }
293
294 /**
295  * Whether the current URL is within the comments popup window.
296  *
297  * @see WP_Query::is_comments_popup()
298  * @since 1.5.0
299  * @uses $wp_query
300  *
301  * @return bool
302  */
303 function is_comments_popup() {
304         global $wp_query;
305
306         if ( ! isset( $wp_query ) ) {
307                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
308                 return false;
309         }
310
311         return $wp_query->is_comments_popup();
312 }
313
314 /**
315  * Is the query for an existing date archive?
316  *
317  * @see WP_Query::is_date()
318  * @since 1.5.0
319  * @uses $wp_query
320  *
321  * @return bool
322  */
323 function is_date() {
324         global $wp_query;
325
326         if ( ! isset( $wp_query ) ) {
327                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
328                 return false;
329         }
330
331         return $wp_query->is_date();
332 }
333
334 /**
335  * Is the query for an existing day archive?
336  *
337  * @see WP_Query::is_day()
338  * @since 1.5.0
339  * @uses $wp_query
340  *
341  * @return bool
342  */
343 function is_day() {
344         global $wp_query;
345
346         if ( ! isset( $wp_query ) ) {
347                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
348                 return false;
349         }
350
351         return $wp_query->is_day();
352 }
353
354 /**
355  * Is the query for a feed?
356  *
357  * @see WP_Query::is_feed()
358  * @since 1.5.0
359  * @uses $wp_query
360  *
361  * @param string|array $feeds Optional feed types to check.
362  * @return bool
363  */
364 function is_feed( $feeds = '' ) {
365         global $wp_query;
366
367         if ( ! isset( $wp_query ) ) {
368                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
369                 return false;
370         }
371
372         return $wp_query->is_feed( $feeds );
373 }
374
375 /**
376  * Is the query for a comments feed?
377  *
378  * @see WP_Query::is_comments_feed()
379  * @since 3.0.0
380  * @uses $wp_query
381  *
382  * @return bool
383  */
384 function is_comment_feed() {
385         global $wp_query;
386
387         if ( ! isset( $wp_query ) ) {
388                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
389                 return false;
390         }
391
392         return $wp_query->is_comment_feed();
393 }
394
395 /**
396  * Is the query for the front page of the site?
397  *
398  * This is for what is displayed at your site's main URL.
399  *
400  * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
401  *
402  * If you set a static page for the front page of your site, this function will return
403  * true when viewing that page.
404  *
405  * Otherwise the same as @see is_home()
406  *
407  * @see WP_Query::is_front_page()
408  * @since 2.5.0
409  *
410  * @return bool True, if front of site.
411  */
412 function is_front_page() {
413         global $wp_query;
414
415         if ( ! isset( $wp_query ) ) {
416                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
417                 return false;
418         }
419
420         return $wp_query->is_front_page();
421 }
422
423 /**
424  * Is the query for the blog homepage?
425  *
426  * This is the page which shows the time based blog content of your site.
427  *
428  * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
429  *
430  * If you set a static page for the front page of your site, this function will return
431  * true only on the page you set as the "Posts page".
432  *
433  * @see is_front_page()
434  *
435  * @see WP_Query::is_home()
436  * @since 1.5.0
437  * @uses $wp_query
438  *
439  * @return bool True if blog view homepage.
440  */
441 function is_home() {
442         global $wp_query;
443
444         if ( ! isset( $wp_query ) ) {
445                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
446                 return false;
447         }
448
449         return $wp_query->is_home();
450 }
451
452 /**
453  * Is the query for an existing month archive?
454  *
455  * @see WP_Query::is_month()
456  * @since 1.5.0
457  * @uses $wp_query
458  *
459  * @return bool
460  */
461 function is_month() {
462         global $wp_query;
463
464         if ( ! isset( $wp_query ) ) {
465                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
466                 return false;
467         }
468
469         return $wp_query->is_month();
470 }
471
472 /**
473  * Is the query for an existing single page?
474  *
475  * If the $page parameter is specified, this function will additionally
476  * check if the query is for one of the pages specified.
477  *
478  * @see is_single()
479  * @see is_singular()
480  *
481  * @see WP_Query::is_page()
482  * @since 1.5.0
483  * @uses $wp_query
484  *
485  * @param mixed $page Page ID, title, slug, or array of such.
486  * @return bool
487  */
488 function is_page( $page = '' ) {
489         global $wp_query;
490
491         if ( ! isset( $wp_query ) ) {
492                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
493                 return false;
494         }
495
496         return $wp_query->is_page( $page );
497 }
498
499 /**
500  * Is the query for paged result and not for the first page?
501  *
502  * @see WP_Query::is_paged()
503  * @since 1.5.0
504  * @uses $wp_query
505  *
506  * @return bool
507  */
508 function is_paged() {
509         global $wp_query;
510
511         if ( ! isset( $wp_query ) ) {
512                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
513                 return false;
514         }
515
516         return $wp_query->is_paged();
517 }
518
519 /**
520  * Is the query for a post or page preview?
521  *
522  * @see WP_Query::is_preview()
523  * @since 2.0.0
524  * @uses $wp_query
525  *
526  * @return bool
527  */
528 function is_preview() {
529         global $wp_query;
530
531         if ( ! isset( $wp_query ) ) {
532                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
533                 return false;
534         }
535
536         return $wp_query->is_preview();
537 }
538
539 /**
540  * Is the query for the robots file?
541  *
542  * @see WP_Query::is_robots()
543  * @since 2.1.0
544  * @uses $wp_query
545  *
546  * @return bool
547  */
548 function is_robots() {
549         global $wp_query;
550
551         if ( ! isset( $wp_query ) ) {
552                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
553                 return false;
554         }
555
556         return $wp_query->is_robots();
557 }
558
559 /**
560  * Is the query for a search?
561  *
562  * @see WP_Query::is_search()
563  * @since 1.5.0
564  * @uses $wp_query
565  *
566  * @return bool
567  */
568 function is_search() {
569         global $wp_query;
570
571         if ( ! isset( $wp_query ) ) {
572                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
573                 return false;
574         }
575
576         return $wp_query->is_search();
577 }
578
579 /**
580  * Is the query for an existing single post?
581  *
582  * Works for any post type, except attachments and pages
583  *
584  * If the $post parameter is specified, this function will additionally
585  * check if the query is for one of the Posts specified.
586  *
587  * @see is_page()
588  * @see is_singular()
589  *
590  * @see WP_Query::is_single()
591  * @since 1.5.0
592  * @uses $wp_query
593  *
594  * @param mixed $post Post ID, title, slug, or array of such.
595  * @return bool
596  */
597 function is_single( $post = '' ) {
598         global $wp_query;
599
600         if ( ! isset( $wp_query ) ) {
601                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
602                 return false;
603         }
604
605         return $wp_query->is_single( $post );
606 }
607
608 /**
609  * Is the query for an existing single post of any post type (post, attachment, page, ... )?
610  *
611  * If the $post_types parameter is specified, this function will additionally
612  * check if the query is for one of the Posts Types specified.
613  *
614  * @see is_page()
615  * @see is_single()
616  *
617  * @see WP_Query::is_singular()
618  * @since 1.5.0
619  * @uses $wp_query
620  *
621  * @param mixed $post_types Optional. Post Type or array of Post Types
622  * @return bool
623  */
624 function is_singular( $post_types = '' ) {
625         global $wp_query;
626
627         if ( ! isset( $wp_query ) ) {
628                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
629                 return false;
630         }
631
632         return $wp_query->is_singular( $post_types );
633 }
634
635 /**
636  * Is the query for a specific time?
637  *
638  * @see WP_Query::is_time()
639  * @since 1.5.0
640  * @uses $wp_query
641  *
642  * @return bool
643  */
644 function is_time() {
645         global $wp_query;
646
647         if ( ! isset( $wp_query ) ) {
648                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
649                 return false;
650         }
651
652         return $wp_query->is_time();
653 }
654
655 /**
656  * Is the query for a trackback endpoint call?
657  *
658  * @see WP_Query::is_trackback()
659  * @since 1.5.0
660  * @uses $wp_query
661  *
662  * @return bool
663  */
664 function is_trackback() {
665         global $wp_query;
666
667         if ( ! isset( $wp_query ) ) {
668                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
669                 return false;
670         }
671
672         return $wp_query->is_trackback();
673 }
674
675 /**
676  * Is the query for an existing year archive?
677  *
678  * @see WP_Query::is_year()
679  * @since 1.5.0
680  * @uses $wp_query
681  *
682  * @return bool
683  */
684 function is_year() {
685         global $wp_query;
686
687         if ( ! isset( $wp_query ) ) {
688                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
689                 return false;
690         }
691
692         return $wp_query->is_year();
693 }
694
695 /**
696  * Is the query a 404 (returns no results)?
697  *
698  * @see WP_Query::is_404()
699  * @since 1.5.0
700  * @uses $wp_query
701  *
702  * @return bool
703  */
704 function is_404() {
705         global $wp_query;
706
707         if ( ! isset( $wp_query ) ) {
708                 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
709                 return false;
710         }
711
712         return $wp_query->is_404();
713 }
714
715 /**
716  * Is the query the main query?
717  *
718  * @since 3.3.0
719  *
720  * @return bool
721  */
722 function is_main_query() {
723         if ( 'pre_get_posts' === current_filter() ) {
724                 $message = sprintf( __( 'In <code>%1$s</code>, use the <code>%2$s</code> method, not the <code>%3$s</code> function. See %4$s.' ),
725                         'pre_get_posts', 'WP_Query::is_main_query()', 'is_main_query()', __( 'http://codex.wordpress.org/Function_Reference/is_main_query' ) );
726                 _doing_it_wrong( __FUNCTION__, $message, '3.7' );
727         }
728
729         global $wp_query;
730         return $wp_query->is_main_query();
731 }
732
733 /*
734  * The Loop. Post loop control.
735  */
736
737 /**
738  * Whether current WordPress query has results to loop over.
739  *
740  * @see WP_Query::have_posts()
741  * @since 1.5.0
742  * @uses $wp_query
743  *
744  * @return bool
745  */
746 function have_posts() {
747         global $wp_query;
748
749         return $wp_query->have_posts();
750 }
751
752 /**
753  * Whether the caller is in the Loop.
754  *
755  * @since 2.0.0
756  * @uses $wp_query
757  *
758  * @return bool True if caller is within loop, false if loop hasn't started or ended.
759  */
760 function in_the_loop() {
761         global $wp_query;
762
763         return $wp_query->in_the_loop;
764 }
765
766 /**
767  * Rewind the loop posts.
768  *
769  * @see WP_Query::rewind_posts()
770  * @since 1.5.0
771  * @uses $wp_query
772  *
773  * @return null
774  */
775 function rewind_posts() {
776         global $wp_query;
777
778         return $wp_query->rewind_posts();
779 }
780
781 /**
782  * Iterate the post index in the loop.
783  *
784  * @see WP_Query::the_post()
785  * @since 1.5.0
786  * @uses $wp_query
787  */
788 function the_post() {
789         global $wp_query;
790
791         $wp_query->the_post();
792 }
793
794 /*
795  * Comments loop.
796  */
797
798 /**
799  * Whether there are comments to loop over.
800  *
801  * @see WP_Query::have_comments()
802  * @since 2.2.0
803  * @uses $wp_query
804  *
805  * @return bool
806  */
807 function have_comments() {
808         global $wp_query;
809         return $wp_query->have_comments();
810 }
811
812 /**
813  * Iterate comment index in the comment loop.
814  *
815  * @see WP_Query::the_comment()
816  * @since 2.2.0
817  * @uses $wp_query
818  *
819  * @return object
820  */
821 function the_comment() {
822         global $wp_query;
823         return $wp_query->the_comment();
824 }
825
826 /*
827  * WP_Query
828  */
829
830 /**
831  * The WordPress Query class.
832  *
833  * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
834  *
835  * @since 1.5.0
836  */
837 class WP_Query {
838
839         /**
840          * Query vars set by the user
841          *
842          * @since 1.5.0
843          * @access public
844          * @var array
845          */
846         public $query;
847
848         /**
849          * Query vars, after parsing
850          *
851          * @since 1.5.0
852          * @access public
853          * @var array
854          */
855         public $query_vars = array();
856
857         /**
858          * Taxonomy query, as passed to get_tax_sql()
859          *
860          * @since 3.1.0
861          * @access public
862          * @var object WP_Tax_Query
863          */
864         public $tax_query;
865
866         /**
867          * Metadata query container
868          *
869          * @since 3.2.0
870          * @access public
871          * @var object WP_Meta_Query
872          */
873         public $meta_query = false;
874
875         /**
876          * Date query container
877          *
878          * @since 3.7.0
879          * @access public
880          * @var object WP_Date_Query
881          */
882         public $date_query = false;
883
884         /**
885          * Holds the data for a single object that is queried.
886          *
887          * Holds the contents of a post, page, category, attachment.
888          *
889          * @since 1.5.0
890          * @access public
891          * @var object|array
892          */
893         public $queried_object;
894
895         /**
896          * The ID of the queried object.
897          *
898          * @since 1.5.0
899          * @access public
900          * @var int
901          */
902         public $queried_object_id;
903
904         /**
905          * Get post database query.
906          *
907          * @since 2.0.1
908          * @access public
909          * @var string
910          */
911         public $request;
912
913         /**
914          * List of posts.
915          *
916          * @since 1.5.0
917          * @access public
918          * @var array
919          */
920         public $posts;
921
922         /**
923          * The amount of posts for the current query.
924          *
925          * @since 1.5.0
926          * @access public
927          * @var int
928          */
929         public $post_count = 0;
930
931         /**
932          * Index of the current item in the loop.
933          *
934          * @since 1.5.0
935          * @access public
936          * @var int
937          */
938         public $current_post = -1;
939
940         /**
941          * Whether the loop has started and the caller is in the loop.
942          *
943          * @since 2.0.0
944          * @access public
945          * @var bool
946          */
947         public $in_the_loop = false;
948
949         /**
950          * The current post.
951          *
952          * @since 1.5.0
953          * @access public
954          * @var WP_Post
955          */
956         public $post;
957
958         /**
959          * The list of comments for current post.
960          *
961          * @since 2.2.0
962          * @access public
963          * @var array
964          */
965         public $comments;
966
967         /**
968          * The amount of comments for the posts.
969          *
970          * @since 2.2.0
971          * @access public
972          * @var int
973          */
974         public $comment_count = 0;
975
976         /**
977          * The index of the comment in the comment loop.
978          *
979          * @since 2.2.0
980          * @access public
981          * @var int
982          */
983         public $current_comment = -1;
984
985         /**
986          * Current comment ID.
987          *
988          * @since 2.2.0
989          * @access public
990          * @var int
991          */
992         public $comment;
993
994         /**
995          * The amount of found posts for the current query.
996          *
997          * If limit clause was not used, equals $post_count.
998          *
999          * @since 2.1.0
1000          * @access public
1001          * @var int
1002          */
1003         public $found_posts = 0;
1004
1005         /**
1006          * The amount of pages.
1007          *
1008          * @since 2.1.0
1009          * @access public
1010          * @var int
1011          */
1012         public $max_num_pages = 0;
1013
1014         /**
1015          * The amount of comment pages.
1016          *
1017          * @since 2.7.0
1018          * @access public
1019          * @var int
1020          */
1021         public $max_num_comment_pages = 0;
1022
1023         /**
1024          * Set if query is single post.
1025          *
1026          * @since 1.5.0
1027          * @access public
1028          * @var bool
1029          */
1030         public $is_single = false;
1031
1032         /**
1033          * Set if query is preview of blog.
1034          *
1035          * @since 2.0.0
1036          * @access public
1037          * @var bool
1038          */
1039         public $is_preview = false;
1040
1041         /**
1042          * Set if query returns a page.
1043          *
1044          * @since 1.5.0
1045          * @access public
1046          * @var bool
1047          */
1048         public $is_page = false;
1049
1050         /**
1051          * Set if query is an archive list.
1052          *
1053          * @since 1.5.0
1054          * @access public
1055          * @var bool
1056          */
1057         public $is_archive = false;
1058
1059         /**
1060          * Set if query is part of a date.
1061          *
1062          * @since 1.5.0
1063          * @access public
1064          * @var bool
1065          */
1066         public $is_date = false;
1067
1068         /**
1069          * Set if query contains a year.
1070          *
1071          * @since 1.5.0
1072          * @access public
1073          * @var bool
1074          */
1075         public $is_year = false;
1076
1077         /**
1078          * Set if query contains a month.
1079          *
1080          * @since 1.5.0
1081          * @access public
1082          * @var bool
1083          */
1084         public $is_month = false;
1085
1086         /**
1087          * Set if query contains a day.
1088          *
1089          * @since 1.5.0
1090          * @access public
1091          * @var bool
1092          */
1093         public $is_day = false;
1094
1095         /**
1096          * Set if query contains time.
1097          *
1098          * @since 1.5.0
1099          * @access public
1100          * @var bool
1101          */
1102         public $is_time = false;
1103
1104         /**
1105          * Set if query contains an author.
1106          *
1107          * @since 1.5.0
1108          * @access public
1109          * @var bool
1110          */
1111         public $is_author = false;
1112
1113         /**
1114          * Set if query contains category.
1115          *
1116          * @since 1.5.0
1117          * @access public
1118          * @var bool
1119          */
1120         public $is_category = false;
1121
1122         /**
1123          * Set if query contains tag.
1124          *
1125          * @since 2.3.0
1126          * @access public
1127          * @var bool
1128          */
1129         public $is_tag = false;
1130
1131         /**
1132          * Set if query contains taxonomy.
1133          *
1134          * @since 2.5.0
1135          * @access public
1136          * @var bool
1137          */
1138         public $is_tax = false;
1139
1140         /**
1141          * Set if query was part of a search result.
1142          *
1143          * @since 1.5.0
1144          * @access public
1145          * @var bool
1146          */
1147         public $is_search = false;
1148
1149         /**
1150          * Set if query is feed display.
1151          *
1152          * @since 1.5.0
1153          * @access public
1154          * @var bool
1155          */
1156         public $is_feed = false;
1157
1158         /**
1159          * Set if query is comment feed display.
1160          *
1161          * @since 2.2.0
1162          * @access public
1163          * @var bool
1164          */
1165         public $is_comment_feed = false;
1166
1167         /**
1168          * Set if query is trackback.
1169          *
1170          * @since 1.5.0
1171          * @access public
1172          * @var bool
1173          */
1174         public $is_trackback = false;
1175
1176         /**
1177          * Set if query is blog homepage.
1178          *
1179          * @since 1.5.0
1180          * @access public
1181          * @var bool
1182          */
1183         public $is_home = false;
1184
1185         /**
1186          * Set if query couldn't found anything.
1187          *
1188          * @since 1.5.0
1189          * @access public
1190          * @var bool
1191          */
1192         public $is_404 = false;
1193
1194         /**
1195          * Set if query is within comments popup window.
1196          *
1197          * @since 1.5.0
1198          * @access public
1199          * @var bool
1200          */
1201         public $is_comments_popup = false;
1202
1203         /**
1204          * Set if query is paged
1205          *
1206          * @since 1.5.0
1207          * @access public
1208          * @var bool
1209          */
1210         public $is_paged = false;
1211
1212         /**
1213          * Set if query is part of administration page.
1214          *
1215          * @since 1.5.0
1216          * @access public
1217          * @var bool
1218          */
1219         public $is_admin = false;
1220
1221         /**
1222          * Set if query is an attachment.
1223          *
1224          * @since 2.0.0
1225          * @access public
1226          * @var bool
1227          */
1228         public $is_attachment = false;
1229
1230         /**
1231          * Set if is single, is a page, or is an attachment.
1232          *
1233          * @since 2.1.0
1234          * @access public
1235          * @var bool
1236          */
1237         public $is_singular = false;
1238
1239         /**
1240          * Set if query is for robots.
1241          *
1242          * @since 2.1.0
1243          * @access public
1244          * @var bool
1245          */
1246         public $is_robots = false;
1247
1248         /**
1249          * Set if query contains posts.
1250          *
1251          * Basically, the homepage if the option isn't set for the static homepage.
1252          *
1253          * @since 2.1.0
1254          * @access public
1255          * @var bool
1256          */
1257         public $is_posts_page = false;
1258
1259         /**
1260          * Set if query is for a post type archive.
1261          *
1262          * @since 3.1.0
1263          * @access public
1264          * @var bool
1265          */
1266         public $is_post_type_archive = false;
1267
1268         /**
1269          * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
1270          * whether we have to re-parse because something has changed
1271          *
1272          * @since 3.1.0
1273          * @access private
1274          */
1275         private $query_vars_hash = false;
1276
1277         /**
1278          * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
1279          * via pre_get_posts hooks.
1280          *
1281          * @since 3.1.1
1282          * @access private
1283          */
1284         private $query_vars_changed = true;
1285
1286         /**
1287          * Set if post thumbnails are cached
1288          *
1289          * @since 3.2.0
1290          * @access public
1291          * @var bool
1292          */
1293          public $thumbnails_cached = false;
1294
1295         /**
1296          * Cached list of search stopwords.
1297          *
1298          * @since 3.7.0
1299          * @var array
1300          */
1301         private $stopwords;
1302
1303         /**
1304          * Resets query flags to false.
1305          *
1306          * The query flags are what page info WordPress was able to figure out.
1307          *
1308          * @since 2.0.0
1309          * @access private
1310          */
1311         private function init_query_flags() {
1312                 $this->is_single = false;
1313                 $this->is_preview = false;
1314                 $this->is_page = false;
1315                 $this->is_archive = false;
1316                 $this->is_date = false;
1317                 $this->is_year = false;
1318                 $this->is_month = false;
1319                 $this->is_day = false;
1320                 $this->is_time = false;
1321                 $this->is_author = false;
1322                 $this->is_category = false;
1323                 $this->is_tag = false;
1324                 $this->is_tax = false;
1325                 $this->is_search = false;
1326                 $this->is_feed = false;
1327                 $this->is_comment_feed = false;
1328                 $this->is_trackback = false;
1329                 $this->is_home = false;
1330                 $this->is_404 = false;
1331                 $this->is_comments_popup = false;
1332                 $this->is_paged = false;
1333                 $this->is_admin = false;
1334                 $this->is_attachment = false;
1335                 $this->is_singular = false;
1336                 $this->is_robots = false;
1337                 $this->is_posts_page = false;
1338                 $this->is_post_type_archive = false;
1339         }
1340
1341         /**
1342          * Initiates object properties and sets default values.
1343          *
1344          * @since 1.5.0
1345          * @access public
1346          */
1347         public function init() {
1348                 unset($this->posts);
1349                 unset($this->query);
1350                 $this->query_vars = array();
1351                 unset($this->queried_object);
1352                 unset($this->queried_object_id);
1353                 $this->post_count = 0;
1354                 $this->current_post = -1;
1355                 $this->in_the_loop = false;
1356                 unset( $this->request );
1357                 unset( $this->post );
1358                 unset( $this->comments );
1359                 unset( $this->comment );
1360                 $this->comment_count = 0;
1361                 $this->current_comment = -1;
1362                 $this->found_posts = 0;
1363                 $this->max_num_pages = 0;
1364                 $this->max_num_comment_pages = 0;
1365
1366                 $this->init_query_flags();
1367         }
1368
1369         /**
1370          * Reparse the query vars.
1371          *
1372          * @since 1.5.0
1373          * @access public
1374          */
1375         public function parse_query_vars() {
1376                 $this->parse_query();
1377         }
1378
1379         /**
1380          * Fills in the query variables, which do not exist within the parameter.
1381          *
1382          * @since 2.1.0
1383          * @access public
1384          *
1385          * @param array $array Defined query variables.
1386          * @return array Complete query variables with undefined ones filled in empty.
1387          */
1388         public function fill_query_vars($array) {
1389                 $keys = array(
1390                         'error'
1391                         , 'm'
1392                         , 'p'
1393                         , 'post_parent'
1394                         , 'subpost'
1395                         , 'subpost_id'
1396                         , 'attachment'
1397                         , 'attachment_id'
1398                         , 'name'
1399                         , 'static'
1400                         , 'pagename'
1401                         , 'page_id'
1402                         , 'second'
1403                         , 'minute'
1404                         , 'hour'
1405                         , 'day'
1406                         , 'monthnum'
1407                         , 'year'
1408                         , 'w'
1409                         , 'category_name'
1410                         , 'tag'
1411                         , 'cat'
1412                         , 'tag_id'
1413                         , 'author'
1414                         , 'author_name'
1415                         , 'feed'
1416                         , 'tb'
1417                         , 'paged'
1418                         , 'comments_popup'
1419                         , 'meta_key'
1420                         , 'meta_value'
1421                         , 'preview'
1422                         , 's'
1423                         , 'sentence'
1424                         , 'fields'
1425                         , 'menu_order'
1426                 );
1427
1428                 foreach ( $keys as $key ) {
1429                         if ( !isset($array[$key]) )
1430                                 $array[$key] = '';
1431                 }
1432
1433                 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in',
1434                         'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
1435                         'author__in', 'author__not_in' );
1436
1437                 foreach ( $array_keys as $key ) {
1438                         if ( !isset($array[$key]) )
1439                                 $array[$key] = array();
1440                 }
1441                 return $array;
1442         }
1443
1444         /**
1445          * Parse a query string and set query type booleans.
1446          *
1447          * @since 1.5.0
1448          * @access public
1449          *
1450          * @param string|array $query {
1451          *     Optional. Array or string of Query parameters.
1452          *
1453          *     @type int          $attachment_id           Attachment post ID. Used for 'attachment' post_type.
1454          *     @type int|string   $author                  Author ID, or comma-separated list of IDs.
1455          *     @type string       $author_name             User 'user_nicename'.
1456          *     @type array        $author__in              An array of author IDs to query from.
1457          *     @type array        $author__not_in          An array of author IDs not to query from.
1458          *     @type bool         $cache_results           Whether to cache post information. Default true.
1459          *     @type int|string   $cat                     Category ID or comma-separated list of IDs (this or any children).
1460          *     @type array        $category__and           An array of category IDs (AND in).
1461          *     @type array        $category__in            An array of category IDs (OR in, no children).
1462          *     @type array        $category__not_in        An array of category IDs (NOT in).
1463          *     @type string       $category_name           Use category slug (not name, this or any children).
1464          *     @type int          $comments_per_page       The number of comments to return per page.
1465          *                                                 Default 'comments_per_page' option.
1466          *     @type int|string   $comments_popup          Whether the query is within the comments popup. Default empty.
1467          *     @type array        $date_query              An associative array of WP_Date_Query arguments.
1468          *                                                 {@see WP_Date_Query::__construct()}
1469          *     @type int          $day                     Day of the month. Default empty. Accepts numbers 1-31.
1470          *     @type bool         $exact                   Whether to search by exact keyword. Default false.
1471          *     @type string|array $fields                  Which fields to return. Single field or all fields (string),
1472          *                                                 or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
1473          *                                                 Default all fields. Accepts 'ids', 'id=>parent'.
1474          *     @type int          $hour                    Hour of the day. Default empty. Accepts numbers 0-23.
1475          *     @type bool         $ignore_sticky_posts     Whether to ignore sticky posts or not. Setting this to false
1476          *                                                 excludes stickies from 'post__in'. Accepts 1|true, 0|false.
1477          *                                                 Default 0|false.
1478          *     @type int          $m                       Combination YearMonth. Accepts any four-digit year and month
1479          *                                                 numbers 1-12. Default empty.
1480          *     @type string       $meta_compare            Comparison operator to test the 'meta_value'.
1481          *     @type string       $meta_key                Custom field key.
1482          *     @type array        $meta_query              An associative array of WP_Meta_Query arguments.
1483          *                                                 {@see WP_Meta_Query->queries}
1484          *     @type string       $meta_value              Custom field value.
1485          *     @type int          $meta_value_num          Custom field value number.
1486          *     @type int          $menu_order              The menu order of the posts.
1487          *     @type int          $monthnum                The two-digit month. Default empty. Accepts numbers 1-12.
1488          *     @type string       $name                    Post slug.
1489          *     @type bool         $nopaging                Show all posts (true) or paginate (false). Default false.
1490          *     @type bool         $no_found_rows           Whether to skip counting the total rows found. Enabling can improve
1491          *                                                 performance. Default false.
1492          *     @type int          $offset                  The number of posts to offset before retrieval.
1493          *     @type string       $order                   Designates ascending or descending order of posts. Default 'DESC'.
1494          *                                                 Accepts 'ASC', 'DESC'.
1495          *     @type string       $orderby                 Sort retrieved posts by parameter. One or more options can be
1496          *                                                 passed. To use 'meta_value', or 'meta_value_num',
1497          *                                                 'meta_key=keyname' must be also be defined. Default 'date'.
1498          *                                                 Accepts 'none', 'name', 'author', 'date', 'title', 'modified',
1499          *                                                 'menu_order', 'parent', 'ID', 'rand', 'comment_count'.
1500          *     @type int          $p                       Post ID.
1501          *     @type int          $page                    Show the number of posts that would show up on page X of a
1502          *                                                 static front page.
1503          *     @type int          $paged                   The number of the current page.
1504          *     @type int          $page_id                 Page ID.
1505          *     @type string       $pagename                Page slug.
1506          *     @type string       $perm                    Show posts if user has the appropriate capability.
1507          *     @type array        $post__in                An array of post IDs to retrieve, sticky posts will be included
1508          *     @type string       $post_mime_type          The mime type of the post. Used for 'attachment' post_type.
1509          *     @type array        $post__not_in            An array of post IDs not to retrieve. Note: a string of comma-
1510          *                                                 separated IDs will NOT work.
1511          *     @type int          $post_parent             Page ID to retrieve child pages for. Use 0 to only retrieve
1512          *                                                 top-level pages.
1513          *     @type array        $post_parent__in         An array containing parent page IDs to query child pages from.
1514          *     @type array        $post_parent__not_in     An array containing parent page IDs not to query child pages from.
1515          *     @type string|array $post_type               A post type slug (string) or array of post type slugs.
1516          *                                                 Default 'any' if using 'tax_query'.
1517          *     @type string|array $post_status             A post status (string) or array of post statuses.
1518          *     @type int          $posts_per_page          The number of posts to query for. Use -1 to request all posts.
1519          *     @type int          $posts_per_archive_page  The number of posts to query for by archive page. Overrides
1520          *                                                 'posts_per_page' when is_archive(), or is_search() are true.
1521          *     @type string       $s                       Search keyword.
1522          *     @type int          $second                  Second of the minute. Default empty. Accepts numbers 0-60.
1523          *     @type array        $search_terms            Array of search terms.
1524          *     @type bool         $sentence                Whether to search by phrase. Default false.
1525          *     @type bool         $suppress_filters        Whether to suppress filters. Default false.
1526          *     @type string       $tag                     Tag slug. Comma-separated (either), Plus-separated (all).
1527          *     @type array        $tag__and                An array of tag ids (AND in).
1528          *     @type array        $tag__in                 An array of tag ids (OR in).
1529          *     @type array        $tag__not_in             An array of tag ids (NOT in).
1530          *     @type int          $tag_id                  Tag id or comma-separated list of IDs.
1531          *     @type array        $tag_slug__and           An array of tag slugs (AND in).
1532          *     @type array        $tag_slug__in            An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
1533          *                                                 true. Note: a string of comma-separated IDs will NOT work.
1534          *     @type array        $tax_query               An associative array of WP_Tax_Query arguments.
1535          *                                                 {@see WP_Tax_Query->queries}
1536          *     @type bool         $update_post_meta_cache  Whether to update the post meta cache. Default true.
1537          *     @type bool         $update_post_term_cache  Whether to update the post term cache. Default true.
1538          *     @type int          $w                       The week number of the year. Default empty. Accepts numbers 0-53.
1539          *     @type int          $year                    The four-digit year. Default empty. Accepts any four-digit year.
1540          * }
1541          */
1542         public function parse_query( $query =  '' ) {
1543                 if ( ! empty( $query ) ) {
1544                         $this->init();
1545                         $this->query = $this->query_vars = wp_parse_args( $query );
1546                 } elseif ( ! isset( $this->query ) ) {
1547                         $this->query = $this->query_vars;
1548                 }
1549
1550                 $this->query_vars = $this->fill_query_vars($this->query_vars);
1551                 $qv = &$this->query_vars;
1552                 $this->query_vars_changed = true;
1553
1554                 if ( ! empty($qv['robots']) )
1555                         $this->is_robots = true;
1556
1557                 $qv['p'] =  absint($qv['p']);
1558                 $qv['page_id'] =  absint($qv['page_id']);
1559                 $qv['year'] = absint($qv['year']);
1560                 $qv['monthnum'] = absint($qv['monthnum']);
1561                 $qv['day'] = absint($qv['day']);
1562                 $qv['w'] = absint($qv['w']);
1563                 $qv['m'] = preg_replace( '|[^0-9]|', '', $qv['m'] );
1564                 $qv['paged'] = absint($qv['paged']);
1565                 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1566                 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
1567                 $qv['pagename'] = trim( $qv['pagename'] );
1568                 $qv['name'] = trim( $qv['name'] );
1569                 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1570                 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1571                 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1572                 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
1573
1574                 // Fairly insane upper bound for search string lengths.
1575                 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
1576                         $qv['s'] = '';
1577                 }
1578
1579                 // Compat. Map subpost to attachment.
1580                 if ( '' != $qv['subpost'] )
1581                         $qv['attachment'] = $qv['subpost'];
1582                 if ( '' != $qv['subpost_id'] )
1583                         $qv['attachment_id'] = $qv['subpost_id'];
1584
1585                 $qv['attachment_id'] = absint($qv['attachment_id']);
1586
1587                 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1588                         $this->is_single = true;
1589                         $this->is_attachment = true;
1590                 } elseif ( '' != $qv['name'] ) {
1591                         $this->is_single = true;
1592                 } elseif ( $qv['p'] ) {
1593                         $this->is_single = true;
1594                 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1595                         // If year, month, day, hour, minute, and second are set, a single
1596                         // post is being queried.
1597                         $this->is_single = true;
1598                 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1599                         $this->is_page = true;
1600                         $this->is_single = false;
1601                 } else {
1602                         // Look for archive queries. Dates, categories, authors, search, post type archives.
1603
1604                         if ( isset( $this->query['s'] ) ) {
1605                                 $this->is_search = true;
1606                         }
1607
1608                         if ( '' !== $qv['second'] ) {
1609                                 $this->is_time = true;
1610                                 $this->is_date = true;
1611                         }
1612
1613                         if ( '' !== $qv['minute'] ) {
1614                                 $this->is_time = true;
1615                                 $this->is_date = true;
1616                         }
1617
1618                         if ( '' !== $qv['hour'] ) {
1619                                 $this->is_time = true;
1620                                 $this->is_date = true;
1621                         }
1622
1623                         if ( $qv['day'] ) {
1624                                 if ( ! $this->is_date ) {
1625                                         $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
1626                                         if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
1627                                                 $qv['error'] = '404';
1628                                         } else {
1629                                                 $this->is_day = true;
1630                                                 $this->is_date = true;
1631                                         }
1632                                 }
1633                         }
1634
1635                         if ( $qv['monthnum'] ) {
1636                                 if ( ! $this->is_date ) {
1637                                         if ( 12 < $qv['monthnum'] ) {
1638                                                 $qv['error'] = '404';
1639                                         } else {
1640                                                 $this->is_month = true;
1641                                                 $this->is_date = true;
1642                                         }
1643                                 }
1644                         }
1645
1646                         if ( $qv['year'] ) {
1647                                 if ( ! $this->is_date ) {
1648                                         $this->is_year = true;
1649                                         $this->is_date = true;
1650                                 }
1651                         }
1652
1653                         if ( $qv['m'] ) {
1654                                 $this->is_date = true;
1655                                 if ( strlen($qv['m']) > 9 ) {
1656                                         $this->is_time = true;
1657                                 } else if ( strlen($qv['m']) > 7 ) {
1658                                         $this->is_day = true;
1659                                 } else if ( strlen($qv['m']) > 5 ) {
1660                                         $this->is_month = true;
1661                                 } else {
1662                                         $this->is_year = true;
1663                                 }
1664                         }
1665
1666                         if ( '' != $qv['w'] ) {
1667                                 $this->is_date = true;
1668                         }
1669
1670                         $this->query_vars_hash = false;
1671                         $this->parse_tax_query( $qv );
1672
1673                         foreach ( $this->tax_query->queries as $tax_query ) {
1674                                 if ( ! is_array( $tax_query ) ) {
1675                                         continue;
1676                                 }
1677
1678                                 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
1679                                         switch ( $tax_query['taxonomy'] ) {
1680                                                 case 'category':
1681                                                         $this->is_category = true;
1682                                                         break;
1683                                                 case 'post_tag':
1684                                                         $this->is_tag = true;
1685                                                         break;
1686                                                 default:
1687                                                         $this->is_tax = true;
1688                                         }
1689                                 }
1690                         }
1691                         unset( $tax_query );
1692
1693                         if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1694                                 $this->is_author = false;
1695                         } else {
1696                                 $this->is_author = true;
1697                         }
1698
1699                         if ( '' != $qv['author_name'] )
1700                                 $this->is_author = true;
1701
1702                         if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
1703                                 $post_type_obj = get_post_type_object( $qv['post_type'] );
1704                                 if ( ! empty( $post_type_obj->has_archive ) )
1705                                         $this->is_post_type_archive = true;
1706                         }
1707
1708                         if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
1709                                 $this->is_archive = true;
1710                 }
1711
1712                 if ( '' != $qv['feed'] )
1713                         $this->is_feed = true;
1714
1715                 if ( '' != $qv['tb'] )
1716                         $this->is_trackback = true;
1717
1718                 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
1719                         $this->is_paged = true;
1720
1721                 if ( '' != $qv['comments_popup'] )
1722                         $this->is_comments_popup = true;
1723
1724                 // if we're previewing inside the write screen
1725                 if ( '' != $qv['preview'] )
1726                         $this->is_preview = true;
1727
1728                 if ( is_admin() )
1729                         $this->is_admin = true;
1730
1731                 if ( false !== strpos($qv['feed'], 'comments-') ) {
1732                         $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1733                         $qv['withcomments'] = 1;
1734                 }
1735
1736                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1737
1738                 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1739                         $this->is_comment_feed = true;
1740
1741                 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup || $this->is_robots ) )
1742                         $this->is_home = true;
1743
1744                 // Correct is_* for page_on_front and page_for_posts
1745                 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1746                         $_query = wp_parse_args($this->query);
1747                         // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
1748                         if ( isset($_query['pagename']) && '' == $_query['pagename'] )
1749                                 unset($_query['pagename']);
1750                         if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
1751                                 $this->is_page = true;
1752                                 $this->is_home = false;
1753                                 $qv['page_id'] = get_option('page_on_front');
1754                                 // Correct <!--nextpage--> for page_on_front
1755                                 if ( !empty($qv['paged']) ) {
1756                                         $qv['page'] = $qv['paged'];
1757                                         unset($qv['paged']);
1758                                 }
1759                         }
1760                 }
1761
1762                 if ( '' != $qv['pagename'] ) {
1763                         $this->queried_object = get_page_by_path($qv['pagename']);
1764                         if ( !empty($this->queried_object) )
1765                                 $this->queried_object_id = (int) $this->queried_object->ID;
1766                         else
1767                                 unset($this->queried_object);
1768
1769                         if  ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1770                                 $this->is_page = false;
1771                                 $this->is_home = true;
1772                                 $this->is_posts_page = true;
1773                         }
1774                 }
1775
1776                 if ( $qv['page_id'] ) {
1777                         if  ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1778                                 $this->is_page = false;
1779                                 $this->is_home = true;
1780                                 $this->is_posts_page = true;
1781                         }
1782                 }
1783
1784                 if ( !empty($qv['post_type']) ) {
1785                         if ( is_array($qv['post_type']) )
1786                                 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1787                         else
1788                                 $qv['post_type'] = sanitize_key($qv['post_type']);
1789                 }
1790
1791                 if ( ! empty( $qv['post_status'] ) ) {
1792                         if ( is_array( $qv['post_status'] ) )
1793                                 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1794                         else
1795                                 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1796                 }
1797
1798                 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1799                         $this->is_comment_feed = false;
1800
1801                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1802                 // Done correcting is_* for page_on_front and page_for_posts
1803
1804                 if ( '404' == $qv['error'] )
1805                         $this->set_404();
1806
1807                 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1808                 $this->query_vars_changed = false;
1809
1810                 /**
1811                  * Fires after the main query vars have been parsed.
1812                  *
1813                  * @since 1.5.0
1814                  *
1815                  * @param WP_Query &$this The WP_Query instance (passed by reference).
1816                  */
1817                 do_action_ref_array( 'parse_query', array( &$this ) );
1818         }
1819
1820         /**
1821          * Parses various taxonomy related query vars.
1822          *
1823          * For BC, this method is not marked as protected. See [28987].
1824          *
1825          * @access protected
1826          * @since 3.1.0
1827          *
1828          * @param array &$q The query variables
1829          */
1830         function parse_tax_query( &$q ) {
1831                 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1832                         $tax_query = $q['tax_query'];
1833                 } else {
1834                         $tax_query = array();
1835                 }
1836
1837                 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1838                         $tax_query[] = array(
1839                                 'taxonomy' => $q['taxonomy'],
1840                                 'terms' => array( $q['term'] ),
1841                                 'field' => 'slug',
1842                         );
1843                 }
1844
1845                 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1846                         if ( 'post_tag' == $taxonomy )
1847                                 continue;       // Handled further down in the $q['tag'] block
1848
1849                         if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1850                                 $tax_query_defaults = array(
1851                                         'taxonomy' => $taxonomy,
1852                                         'field' => 'slug',
1853                                 );
1854
1855                                 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1856                                         $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1857                                 }
1858
1859                                 $term = $q[$t->query_var];
1860
1861                                 if ( strpos($term, '+') !== false ) {
1862                                         $terms = preg_split( '/[+]+/', $term );
1863                                         foreach ( $terms as $term ) {
1864                                                 $tax_query[] = array_merge( $tax_query_defaults, array(
1865                                                         'terms' => array( $term )
1866                                                 ) );
1867                                         }
1868                                 } else {
1869                                         $tax_query[] = array_merge( $tax_query_defaults, array(
1870                                                 'terms' => preg_split( '/[,]+/', $term )
1871                                         ) );
1872                                 }
1873                         }
1874                 }
1875
1876                 // Category stuff
1877                 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1878                         $cat_in = $cat_not_in = array();
1879
1880                         $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1881                         $cat_array = array_map( 'intval', $cat_array );
1882                         $q['cat'] = implode( ',', $cat_array );
1883
1884                         foreach ( $cat_array as $cat ) {
1885                                 if ( $cat > 0 )
1886                                         $cat_in[] = $cat;
1887                                 elseif ( $cat < 0 )
1888                                         $cat_not_in[] = abs( $cat );
1889                         }
1890
1891                         if ( ! empty( $cat_in ) ) {
1892                                 $tax_query[] = array(
1893                                         'taxonomy' => 'category',
1894                                         'terms' => $cat_in,
1895                                         'field' => 'term_id',
1896                                         'include_children' => true
1897                                 );
1898                         }
1899
1900                         if ( ! empty( $cat_not_in ) ) {
1901                                 $tax_query[] = array(
1902                                         'taxonomy' => 'category',
1903                                         'terms' => $cat_not_in,
1904                                         'field' => 'term_id',
1905                                         'operator' => 'NOT IN',
1906                                         'include_children' => true
1907                                 );
1908                         }
1909                         unset( $cat_array, $cat_in, $cat_not_in );
1910                 }
1911
1912                 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1913                         $q['category__and'] = (array) $q['category__and'];
1914                         if ( ! isset( $q['category__in'] ) )
1915                                 $q['category__in'] = array();
1916                         $q['category__in'][] = absint( reset( $q['category__and'] ) );
1917                         unset( $q['category__and'] );
1918                 }
1919
1920                 if ( ! empty( $q['category__in'] ) ) {
1921                         $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1922                         $tax_query[] = array(
1923                                 'taxonomy' => 'category',
1924                                 'terms' => $q['category__in'],
1925                                 'field' => 'term_id',
1926                                 'include_children' => false
1927                         );
1928                 }
1929
1930                 if ( ! empty($q['category__not_in']) ) {
1931                         $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
1932                         $tax_query[] = array(
1933                                 'taxonomy' => 'category',
1934                                 'terms' => $q['category__not_in'],
1935                                 'operator' => 'NOT IN',
1936                                 'include_children' => false
1937                         );
1938                 }
1939
1940                 if ( ! empty($q['category__and']) ) {
1941                         $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
1942                         $tax_query[] = array(
1943                                 'taxonomy' => 'category',
1944                                 'terms' => $q['category__and'],
1945                                 'field' => 'term_id',
1946                                 'operator' => 'AND',
1947                                 'include_children' => false
1948                         );
1949                 }
1950
1951                 // Tag stuff
1952                 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
1953                         if ( strpos($q['tag'], ',') !== false ) {
1954                                 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
1955                                 foreach ( (array) $tags as $tag ) {
1956                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1957                                         $q['tag_slug__in'][] = $tag;
1958                                 }
1959                         } else if ( preg_match('/[+\r\n\t ]+/', $q['tag']) || !empty($q['cat']) ) {
1960                                 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
1961                                 foreach ( (array) $tags as $tag ) {
1962                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1963                                         $q['tag_slug__and'][] = $tag;
1964                                 }
1965                         } else {
1966                                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1967                                 $q['tag_slug__in'][] = $q['tag'];
1968                         }
1969                 }
1970
1971                 if ( !empty($q['tag_id']) ) {
1972                         $q['tag_id'] = absint( $q['tag_id'] );
1973                         $tax_query[] = array(
1974                                 'taxonomy' => 'post_tag',
1975                                 'terms' => $q['tag_id']
1976                         );
1977                 }
1978
1979                 if ( !empty($q['tag__in']) ) {
1980                         $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
1981                         $tax_query[] = array(
1982                                 'taxonomy' => 'post_tag',
1983                                 'terms' => $q['tag__in']
1984                         );
1985                 }
1986
1987                 if ( !empty($q['tag__not_in']) ) {
1988                         $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
1989                         $tax_query[] = array(
1990                                 'taxonomy' => 'post_tag',
1991                                 'terms' => $q['tag__not_in'],
1992                                 'operator' => 'NOT IN'
1993                         );
1994                 }
1995
1996                 if ( !empty($q['tag__and']) ) {
1997                         $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
1998                         $tax_query[] = array(
1999                                 'taxonomy' => 'post_tag',
2000                                 'terms' => $q['tag__and'],
2001                                 'operator' => 'AND'
2002                         );
2003                 }
2004
2005                 if ( !empty($q['tag_slug__in']) ) {
2006                         $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
2007                         $tax_query[] = array(
2008                                 'taxonomy' => 'post_tag',
2009                                 'terms' => $q['tag_slug__in'],
2010                                 'field' => 'slug'
2011                         );
2012                 }
2013
2014                 if ( !empty($q['tag_slug__and']) ) {
2015                         $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
2016                         $tax_query[] = array(
2017                                 'taxonomy' => 'post_tag',
2018                                 'terms' => $q['tag_slug__and'],
2019                                 'field' => 'slug',
2020                                 'operator' => 'AND'
2021                         );
2022                 }
2023
2024                 $this->tax_query = new WP_Tax_Query( $tax_query );
2025
2026                 /**
2027                  * Fires after taxonomy-related query vars have been parsed.
2028                  *
2029                  * @since 3.7.0
2030                  *
2031                  * @param WP_Query $this The WP_Query instance.
2032                  */
2033                 do_action( 'parse_tax_query', $this );
2034         }
2035
2036         /**
2037          * Generate SQL for the WHERE clause based on passed search terms.
2038          *
2039          * @since 3.7.0
2040          *
2041          * @global wpdb $wpdb
2042          * @param array $q Query variables.
2043          * @return string WHERE clause.
2044          */
2045         protected function parse_search( &$q ) {
2046                 global $wpdb;
2047
2048                 $search = '';
2049
2050                 // added slashes screw with quote grouping when done early, so done later
2051                 $q['s'] = stripslashes( $q['s'] );
2052                 if ( empty( $_GET['s'] ) && $this->is_main_query() )
2053                         $q['s'] = urldecode( $q['s'] );
2054                 // there are no line breaks in <input /> fields
2055                 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
2056                 $q['search_terms_count'] = 1;
2057                 if ( ! empty( $q['sentence'] ) ) {
2058                         $q['search_terms'] = array( $q['s'] );
2059                 } else {
2060                         if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
2061                                 $q['search_terms_count'] = count( $matches[0] );
2062                                 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
2063                                 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
2064                                 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
2065                                         $q['search_terms'] = array( $q['s'] );
2066                         } else {
2067                                 $q['search_terms'] = array( $q['s'] );
2068                         }
2069                 }
2070
2071                 $n = ! empty( $q['exact'] ) ? '' : '%';
2072                 $searchand = '';
2073                 $q['search_orderby_title'] = array();
2074                 foreach ( $q['search_terms'] as $term ) {
2075                         if ( $n ) {
2076                                 $like = '%' . $wpdb->esc_like( $term ) . '%';
2077                                 $q['search_orderby_title'][] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like );
2078                         }
2079
2080                         $like = $n . $wpdb->esc_like( $term ) . $n;
2081                         $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title LIKE %s) OR ($wpdb->posts.post_content LIKE %s))", $like, $like );
2082                         $searchand = ' AND ';
2083                 }
2084
2085                 if ( ! empty( $search ) ) {
2086                         $search = " AND ({$search}) ";
2087                         if ( ! is_user_logged_in() )
2088                                 $search .= " AND ($wpdb->posts.post_password = '') ";
2089                 }
2090
2091                 return $search;
2092         }
2093
2094         /**
2095          * Check if the terms are suitable for searching.
2096          *
2097          * Uses an array of stopwords (terms) that are excluded from the separate
2098          * term matching when searching for posts. The list of English stopwords is
2099          * the approximate search engines list, and is translatable.
2100          *
2101          * @since 3.7.0
2102          *
2103          * @param array $terms Terms to check.
2104          * @return array Terms that are not stopwords.
2105          */
2106         protected function parse_search_terms( $terms ) {
2107                 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
2108                 $checked = array();
2109
2110                 $stopwords = $this->get_search_stopwords();
2111
2112                 foreach ( $terms as $term ) {
2113                         // keep before/after spaces when term is for exact match
2114                         if ( preg_match( '/^".+"$/', $term ) )
2115                                 $term = trim( $term, "\"'" );
2116                         else
2117                                 $term = trim( $term, "\"' " );
2118
2119                         // Avoid single A-Z.
2120                         if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z]$/i', $term ) ) )
2121                                 continue;
2122
2123                         if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
2124                                 continue;
2125
2126                         $checked[] = $term;
2127                 }
2128
2129                 return $checked;
2130         }
2131
2132         /**
2133          * Retrieve stopwords used when parsing search terms.
2134          *
2135          * @since 3.7.0
2136          *
2137          * @return array Stopwords.
2138          */
2139         protected function get_search_stopwords() {
2140                 if ( isset( $this->stopwords ) )
2141                         return $this->stopwords;
2142
2143                 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
2144                  * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
2145                  * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
2146                  */
2147                 $words = explode( ',', _x( 'about,an,are,as,at,be,by,com,for,from,how,in,is,it,of,on,or,that,the,this,to,was,what,when,where,who,will,with,www',
2148                         'Comma-separated list of search stopwords in your language' ) );
2149
2150                 $stopwords = array();
2151                 foreach( $words as $word ) {
2152                         $word = trim( $word, "\r\n\t " );
2153                         if ( $word )
2154                                 $stopwords[] = $word;
2155                 }
2156
2157                 /**
2158                  * Filter stopwords used when parsing search terms.
2159                  *
2160                  * @since 3.7.0
2161                  *
2162                  * @param array $stopwords Stopwords.
2163                  */
2164                 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
2165                 return $this->stopwords;
2166         }
2167
2168         /**
2169          * Generate SQL for the ORDER BY condition based on passed search terms.
2170          *
2171          * @global wpdb $wpdb
2172          * @param array $q Query variables.
2173          * @return string ORDER BY clause.
2174          */
2175         protected function parse_search_order( &$q ) {
2176                 global $wpdb;
2177
2178                 if ( $q['search_terms_count'] > 1 ) {
2179                         $num_terms = count( $q['search_orderby_title'] );
2180                         $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
2181
2182                         $search_orderby = '(CASE ';
2183                         // sentence match in 'post_title'
2184                         $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_title LIKE %s THEN 1 ", $like );
2185
2186                         // sanity limit, sort as sentence when more than 6 terms
2187                         // (few searches are longer than 6 terms and most titles are not)
2188                         if ( $num_terms < 7 ) {
2189                                 // all words in title
2190                                 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
2191                                 // any word in title, not needed when $num_terms == 1
2192                                 if ( $num_terms > 1 )
2193                                         $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
2194                         }
2195
2196                         // sentence match in 'post_content'
2197                         $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 4 ", $like );
2198                         $search_orderby .= 'ELSE 5 END)';
2199                 } else {
2200                         // single word or sentence search
2201                         $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2202                 }
2203
2204                 return $search_orderby;
2205         }
2206
2207         /**
2208          * If the passed orderby value is allowed, convert the alias to a
2209          * properly-prefixed orderby value.
2210          *
2211          * @since 4.0.0
2212          * @access protected
2213          *
2214          * @global wpdb $wpdb WordPress database abstraction object.
2215          *
2216          * @param string $orderby Alias for the field to order by.
2217          * @return string|bool Table-prefixed value to used in the ORDER clause. False otherwise.
2218          */
2219         protected function parse_orderby( $orderby ) {
2220                 global $wpdb;
2221
2222                 // Used to filter values.
2223                 $allowed_keys = array(
2224                         'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2225                         'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2226                         'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2227                 );
2228
2229                 $primary_meta_key = '';
2230                 $primary_meta_query = false;
2231                 if ( ! empty( $this->meta_query->queries ) ) {
2232                         $primary_meta_query = reset( $this->meta_query->queries );
2233
2234                         if ( ! empty( $primary_meta_query['key'] ) ) {
2235                                 $primary_meta_key = $primary_meta_query['key'];
2236                                 $allowed_keys[] = $primary_meta_key;
2237                         }
2238
2239                         $allowed_keys[] = 'meta_value';
2240                         $allowed_keys[] = 'meta_value_num';
2241                 }
2242
2243                 if ( ! in_array( $orderby, $allowed_keys ) ) {
2244                         return false;
2245                 }
2246
2247                 switch ( $orderby ) {
2248                         case 'post_name':
2249                         case 'post_author':
2250                         case 'post_date':
2251                         case 'post_title':
2252                         case 'post_modified':
2253                         case 'post_parent':
2254                         case 'post_type':
2255                         case 'ID':
2256                         case 'menu_order':
2257                         case 'comment_count':
2258                                 $orderby = "$wpdb->posts.{$orderby}";
2259                                 break;
2260                         case 'rand':
2261                                 $orderby = 'RAND()';
2262                                 break;
2263                         case $primary_meta_key:
2264                         case 'meta_value':
2265                                 if ( ! empty( $primary_meta_query['type'] ) ) {
2266                                         $sql_type = $this->meta_query->get_cast_for_type( $primary_meta_query['type'] );
2267                                         $orderby = "CAST($wpdb->postmeta.meta_value AS {$sql_type})";
2268                                 } else {
2269                                         $orderby = "$wpdb->postmeta.meta_value";
2270                                 }
2271                                 break;
2272                         case 'meta_value_num':
2273                                 $orderby = "$wpdb->postmeta.meta_value+0";
2274                                 break;
2275                         default:
2276                                 $orderby = "$wpdb->posts.post_" . $orderby;
2277                                 break;
2278                 }
2279
2280                 return $orderby;
2281         }
2282
2283         /**
2284          * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2285          *
2286          * @since 4.0.0
2287          * @access protected
2288          *
2289          * @param string $order The 'order' query variable.
2290          * @return string The sanitized 'order' query variable.
2291          */
2292         protected function parse_order( $order ) {
2293                 if ( ! is_string( $order ) || empty( $order ) ) {
2294                         return 'DESC';
2295                 }
2296
2297                 if ( 'ASC' === strtoupper( $order ) ) {
2298                         return 'ASC';
2299                 } else {
2300                         return 'DESC';
2301                 }
2302         }
2303
2304         /**
2305          * Sets the 404 property and saves whether query is feed.
2306          *
2307          * @since 2.0.0
2308          * @access public
2309          */
2310         public function set_404() {
2311                 $is_feed = $this->is_feed;
2312
2313                 $this->init_query_flags();
2314                 $this->is_404 = true;
2315
2316                 $this->is_feed = $is_feed;
2317         }
2318
2319         /**
2320          * Retrieve query variable.
2321          *
2322          * @since 1.5.0
2323          * @access public
2324          *
2325          * @param string $query_var Query variable key.
2326          * @param mixed  $default   Value to return if the query variable is not set. Default ''.
2327          * @return mixed
2328          */
2329         public function get( $query_var, $default = '' ) {
2330                 if ( isset( $this->query_vars[ $query_var ] ) ) {
2331                         return $this->query_vars[ $query_var ];
2332                 }
2333
2334                 return $default;
2335         }
2336
2337         /**
2338          * Set query variable.
2339          *
2340          * @since 1.5.0
2341          * @access public
2342          *
2343          * @param string $query_var Query variable key.
2344          * @param mixed $value Query variable value.
2345          */
2346         public function set($query_var, $value) {
2347                 $this->query_vars[$query_var] = $value;
2348         }
2349
2350         /**
2351          * Retrieve the posts based on query variables.
2352          *
2353          * There are a few filters and actions that can be used to modify the post
2354          * database query.
2355          *
2356          * @since 1.5.0
2357          * @access public
2358          *
2359          * @return array List of posts.
2360          */
2361         public function get_posts() {
2362                 global $wpdb;
2363
2364                 $this->parse_query();
2365
2366                 /**
2367                  * Fires after the query variable object is created, but before the actual query is run.
2368                  *
2369                  * Note: If using conditional tags, use the method versions within the passed instance
2370                  * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2371                  * like is_main_query() test against the global $wp_query instance, not the passed one.
2372                  *
2373                  * @since 2.0.0
2374                  *
2375                  * @param WP_Query &$this The WP_Query instance (passed by reference).
2376                  */
2377                 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2378
2379                 // Shorthand.
2380                 $q = &$this->query_vars;
2381
2382                 // Fill again in case pre_get_posts unset some vars.
2383                 $q = $this->fill_query_vars($q);
2384
2385                 // Parse meta query
2386                 $this->meta_query = new WP_Meta_Query();
2387                 $this->meta_query->parse_query_vars( $q );
2388
2389                 // Set a flag if a pre_get_posts hook changed the query vars.
2390                 $hash = md5( serialize( $this->query_vars ) );
2391                 if ( $hash != $this->query_vars_hash ) {
2392                         $this->query_vars_changed = true;
2393                         $this->query_vars_hash = $hash;
2394                 }
2395                 unset($hash);
2396
2397                 // First let's clear some variables
2398                 $distinct = '';
2399                 $whichauthor = '';
2400                 $whichmimetype = '';
2401                 $where = '';
2402                 $limits = '';
2403                 $join = '';
2404                 $search = '';
2405                 $groupby = '';
2406                 $post_status_join = false;
2407                 $page = 1;
2408
2409                 if ( isset( $q['caller_get_posts'] ) ) {
2410                         _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2411                         if ( !isset( $q['ignore_sticky_posts'] ) )
2412                                 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2413                 }
2414
2415                 if ( !isset( $q['ignore_sticky_posts'] ) )
2416                         $q['ignore_sticky_posts'] = false;
2417
2418                 if ( !isset($q['suppress_filters']) )
2419                         $q['suppress_filters'] = false;
2420
2421                 if ( !isset($q['cache_results']) ) {
2422                         if ( wp_using_ext_object_cache() )
2423                                 $q['cache_results'] = false;
2424                         else
2425                                 $q['cache_results'] = true;
2426                 }
2427
2428                 if ( !isset($q['update_post_term_cache']) )
2429                         $q['update_post_term_cache'] = true;
2430
2431                 if ( !isset($q['update_post_meta_cache']) )
2432                         $q['update_post_meta_cache'] = true;
2433
2434                 if ( !isset($q['post_type']) ) {
2435                         if ( $this->is_search )
2436                                 $q['post_type'] = 'any';
2437                         else
2438                                 $q['post_type'] = '';
2439                 }
2440                 $post_type = $q['post_type'];
2441                 if ( empty( $q['posts_per_page'] ) ) {
2442                         $q['posts_per_page'] = get_option( 'posts_per_page' );
2443                 }
2444                 if ( isset($q['showposts']) && $q['showposts'] ) {
2445                         $q['showposts'] = (int) $q['showposts'];
2446                         $q['posts_per_page'] = $q['showposts'];
2447                 }
2448                 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2449                         $q['posts_per_page'] = $q['posts_per_archive_page'];
2450                 if ( !isset($q['nopaging']) ) {
2451                         if ( $q['posts_per_page'] == -1 ) {
2452                                 $q['nopaging'] = true;
2453                         } else {
2454                                 $q['nopaging'] = false;
2455                         }
2456                 }
2457
2458                 if ( $this->is_feed ) {
2459                         // This overrides posts_per_page.
2460                         if ( ! empty( $q['posts_per_rss'] ) ) {
2461                                 $q['posts_per_page'] = $q['posts_per_rss'];
2462                         } else {
2463                                 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2464                         }
2465                         $q['nopaging'] = false;
2466                 }
2467                 $q['posts_per_page'] = (int) $q['posts_per_page'];
2468                 if ( $q['posts_per_page'] < -1 )
2469                         $q['posts_per_page'] = abs($q['posts_per_page']);
2470                 else if ( $q['posts_per_page'] == 0 )
2471                         $q['posts_per_page'] = 1;
2472
2473                 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2474                         $q['comments_per_page'] = get_option('comments_per_page');
2475
2476                 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2477                         $this->is_page = true;
2478                         $this->is_home = false;
2479                         $q['page_id'] = get_option('page_on_front');
2480                 }
2481
2482                 if ( isset($q['page']) ) {
2483                         $q['page'] = trim($q['page'], '/');
2484                         $q['page'] = absint($q['page']);
2485                 }
2486
2487                 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2488                 if ( isset($q['no_found_rows']) )
2489                         $q['no_found_rows'] = (bool) $q['no_found_rows'];
2490                 else
2491                         $q['no_found_rows'] = false;
2492
2493                 switch ( $q['fields'] ) {
2494                         case 'ids':
2495                                 $fields = "$wpdb->posts.ID";
2496                                 break;
2497                         case 'id=>parent':
2498                                 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2499                                 break;
2500                         default:
2501                                 $fields = "$wpdb->posts.*";
2502                 }
2503
2504                 if ( '' !== $q['menu_order'] )
2505                         $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2506
2507                 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2508                 if ( $q['m'] ) {
2509                         $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2510                         if ( strlen($q['m']) > 5 )
2511                                 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2512                         if ( strlen($q['m']) > 7 )
2513                                 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2514                         if ( strlen($q['m']) > 9 )
2515                                 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2516                         if ( strlen($q['m']) > 11 )
2517                                 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2518                         if ( strlen($q['m']) > 13 )
2519                                 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2520                 }
2521
2522                 // Handle the other individual date parameters
2523                 $date_parameters = array();
2524
2525                 if ( '' !== $q['hour'] )
2526                         $date_parameters['hour'] = $q['hour'];
2527
2528                 if ( '' !== $q['minute'] )
2529                         $date_parameters['minute'] = $q['minute'];
2530
2531                 if ( '' !== $q['second'] )
2532                         $date_parameters['second'] = $q['second'];
2533
2534                 if ( $q['year'] )
2535                         $date_parameters['year'] = $q['year'];
2536
2537                 if ( $q['monthnum'] )
2538                         $date_parameters['monthnum'] = $q['monthnum'];
2539
2540                 if ( $q['w'] )
2541                         $date_parameters['week'] = $q['w'];
2542
2543                 if ( $q['day'] )
2544                         $date_parameters['day'] = $q['day'];
2545
2546                 if ( $date_parameters ) {
2547                         $date_query = new WP_Date_Query( array( $date_parameters ) );
2548                         $where .= $date_query->get_sql();
2549                 }
2550                 unset( $date_parameters, $date_query );
2551
2552                 // Handle complex date queries
2553                 if ( ! empty( $q['date_query'] ) ) {
2554                         $this->date_query = new WP_Date_Query( $q['date_query'] );
2555                         $where .= $this->date_query->get_sql();
2556                 }
2557
2558
2559                 // If we've got a post_type AND it's not "any" post_type.
2560                 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2561                         foreach ( (array)$q['post_type'] as $_post_type ) {
2562                                 $ptype_obj = get_post_type_object($_post_type);
2563                                 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2564                                         continue;
2565
2566                                 if ( ! $ptype_obj->hierarchical ) {
2567                                         // Non-hierarchical post types can directly use 'name'.
2568                                         $q['name'] = $q[ $ptype_obj->query_var ];
2569                                 } else {
2570                                         // Hierarchical post types will operate through 'pagename'.
2571                                         $q['pagename'] = $q[ $ptype_obj->query_var ];
2572                                         $q['name'] = '';
2573                                 }
2574
2575                                 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2576                                 break;
2577                         } //end foreach
2578                         unset($ptype_obj);
2579                 }
2580
2581                 if ( '' != $q['name'] ) {
2582                         $q['name'] = sanitize_title_for_query( $q['name'] );
2583                         $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2584                 } elseif ( '' != $q['pagename'] ) {
2585                         if ( isset($this->queried_object_id) ) {
2586                                 $reqpage = $this->queried_object_id;
2587                         } else {
2588                                 if ( 'page' != $q['post_type'] ) {
2589                                         foreach ( (array)$q['post_type'] as $_post_type ) {
2590                                                 $ptype_obj = get_post_type_object($_post_type);
2591                                                 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2592                                                         continue;
2593
2594                                                 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2595                                                 if ( $reqpage )
2596                                                         break;
2597                                         }
2598                                         unset($ptype_obj);
2599                                 } else {
2600                                         $reqpage = get_page_by_path($q['pagename']);
2601                                 }
2602                                 if ( !empty($reqpage) )
2603                                         $reqpage = $reqpage->ID;
2604                                 else
2605                                         $reqpage = 0;
2606                         }
2607
2608                         $page_for_posts = get_option('page_for_posts');
2609                         if  ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2610                                 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2611                                 $q['name'] = $q['pagename'];
2612                                 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2613                                 $reqpage_obj = get_post( $reqpage );
2614                                 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2615                                         $this->is_attachment = true;
2616                                         $post_type = $q['post_type'] = 'attachment';
2617                                         $this->is_page = true;
2618                                         $q['attachment_id'] = $reqpage;
2619                                 }
2620                         }
2621                 } elseif ( '' != $q['attachment'] ) {
2622                         $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2623                         $q['name'] = $q['attachment'];
2624                         $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2625                 }
2626
2627
2628                 if ( intval($q['comments_popup']) )
2629                         $q['p'] = absint($q['comments_popup']);
2630
2631                 // If an attachment is requested by number, let it supersede any post number.
2632                 if ( $q['attachment_id'] )
2633                         $q['p'] = absint($q['attachment_id']);
2634
2635                 // If a post number is specified, load that post
2636                 if ( $q['p'] ) {
2637                         $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2638                 } elseif ( $q['post__in'] ) {
2639                         $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2640                         $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2641                 } elseif ( $q['post__not_in'] ) {
2642                         $post__not_in = implode(',',  array_map( 'absint', $q['post__not_in'] ));
2643                         $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2644                 }
2645
2646                 if ( is_numeric( $q['post_parent'] ) ) {
2647                         $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2648                 } elseif ( $q['post_parent__in'] ) {
2649                         $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2650                         $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2651                 } elseif ( $q['post_parent__not_in'] ) {
2652                         $post_parent__not_in = implode( ',',  array_map( 'absint', $q['post_parent__not_in'] ) );
2653                         $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2654                 }
2655
2656                 if ( $q['page_id'] ) {
2657                         if  ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2658                                 $q['p'] = $q['page_id'];
2659                                 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2660                         }
2661                 }
2662
2663                 // If a search pattern is specified, load the posts that match.
2664                 if ( ! empty( $q['s'] ) ) {
2665                         $search = $this->parse_search( $q );
2666                 }
2667
2668                 /**
2669                  * Filter the search SQL that is used in the WHERE clause of WP_Query.
2670                  *
2671                  * @since 3.0.0
2672                  *
2673                  * @param string   $search Search SQL for WHERE clause.
2674                  * @param WP_Query $this   The current WP_Query object.
2675                  */
2676                 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2677
2678                 // Taxonomies
2679                 if ( !$this->is_singular ) {
2680                         $this->parse_tax_query( $q );
2681
2682                         $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2683
2684                         $join .= $clauses['join'];
2685                         $where .= $clauses['where'];
2686                 }
2687
2688                 if ( $this->is_tax ) {
2689                         if ( empty($post_type) ) {
2690                                 // Do a fully inclusive search for currently registered post types of queried taxonomies
2691                                 $post_type = array();
2692                                 $taxonomies = array_keys( $this->tax_query->queried_terms );
2693                                 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2694                                         $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2695                                         if ( array_intersect( $taxonomies, $object_taxonomies ) )
2696                                                 $post_type[] = $pt;
2697                                 }
2698                                 if ( ! $post_type )
2699                                         $post_type = 'any';
2700                                 elseif ( count( $post_type ) == 1 )
2701                                         $post_type = $post_type[0];
2702
2703                                 $post_status_join = true;
2704                         } elseif ( in_array('attachment', (array) $post_type) ) {
2705                                 $post_status_join = true;
2706                         }
2707                 }
2708
2709                 /*
2710                  * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2711                  * 'category_name' vars are set for backward compatibility.
2712                  */
2713                 if ( ! empty( $this->tax_query->queried_terms ) ) {
2714
2715                         /*
2716                          * Set 'taxonomy', 'term', and 'term_id' to the
2717                          * first taxonomy other than 'post_tag' or 'category'.
2718                          */
2719                         if ( ! isset( $q['taxonomy'] ) ) {
2720                                 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2721                                         if ( empty( $queried_items['terms'][0] ) ) {
2722                                                 continue;
2723                                         }
2724
2725                                         if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2726                                                 $q['taxonomy'] = $queried_taxonomy;
2727
2728                                                 if ( 'slug' === $queried_items['field'] ) {
2729                                                         $q['term'] = $queried_items['terms'][0];
2730                                                 } else {
2731                                                         $q['term_id'] = $queried_items['terms'][0];
2732                                                 }
2733                                         }
2734                                 }
2735                         }
2736
2737                         // 'cat', 'category_name', 'tag_id'
2738                         foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2739                                 if ( empty( $queried_items['terms'][0] ) ) {
2740                                         continue;
2741                                 }
2742
2743                                 if ( 'category' === $queried_taxonomy ) {
2744                                         $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2745                                         if ( $the_cat ) {
2746                                                 $this->set( 'cat', $the_cat->term_id );
2747                                                 $this->set( 'category_name', $the_cat->slug );
2748                                         }
2749                                         unset( $the_cat );
2750                                 }
2751
2752                                 if ( 'post_tag' === $queried_taxonomy ) {
2753                                         $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2754                                         if ( $the_tag ) {
2755                                                 $this->set( 'tag_id', $the_tag->term_id );
2756                                         }
2757                                         unset( $the_tag );
2758                                 }
2759                         }
2760                 }
2761
2762                 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2763                         $groupby = "{$wpdb->posts}.ID";
2764                 }
2765
2766                 // Author/user stuff
2767
2768                 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2769                         $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2770                         $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2771                         foreach ( $authors as $author ) {
2772                                 $key = $author > 0 ? 'author__in' : 'author__not_in';
2773                                 $q[$key][] = abs( $author );
2774                         }
2775                         $q['author'] = implode( ',', $authors );
2776                 }
2777
2778                 if ( ! empty( $q['author__not_in'] ) ) {
2779                         $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2780                         $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2781                 } elseif ( ! empty( $q['author__in'] ) ) {
2782                         $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2783                         $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2784                 }
2785
2786                 // Author stuff for nice URLs
2787
2788                 if ( '' != $q['author_name'] ) {
2789                         if ( strpos($q['author_name'], '/') !== false ) {
2790                                 $q['author_name'] = explode('/', $q['author_name']);
2791                                 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2792                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2793                                 } else {
2794                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2795                                 }
2796                         }
2797                         $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2798                         $q['author'] = get_user_by('slug', $q['author_name']);
2799                         if ( $q['author'] )
2800                                 $q['author'] = $q['author']->ID;
2801                         $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2802                 }
2803
2804                 // MIME-Type stuff for attachment browsing
2805
2806                 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2807                         $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2808
2809                 $where .= $search . $whichauthor . $whichmimetype;
2810
2811                 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2812                 if ( ! isset( $q['order'] ) ) {
2813                         $q['order'] = $rand ? '' : 'DESC';
2814                 } else {
2815                         $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2816                 }
2817
2818                 // Order by.
2819                 if ( empty( $q['orderby'] ) ) {
2820                         /*
2821                          * Boolean false or empty array blanks out ORDER BY,
2822                          * while leaving the value unset or otherwise empty sets the default.
2823                          */
2824                         if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2825                                 $orderby = '';
2826                         } else {
2827                                 $orderby = "$wpdb->posts.post_date " . $q['order'];
2828                         }
2829                 } elseif ( 'none' == $q['orderby'] ) {
2830                         $orderby = '';
2831                 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2832                         $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2833                 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2834                         $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2835                 } else {
2836                         $orderby_array = array();
2837                         if ( is_array( $q['orderby'] ) ) {
2838                                 foreach ( $q['orderby'] as $_orderby => $order ) {
2839                                         $orderby = addslashes_gpc( urldecode( $_orderby ) );
2840                                         $parsed  = $this->parse_orderby( $orderby );
2841
2842                                         if ( ! $parsed ) {
2843                                                 continue;
2844                                         }
2845
2846                                         $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2847                                 }
2848                                 $orderby = implode( ', ', $orderby_array );
2849
2850                         } else {
2851                                 $q['orderby'] = urldecode( $q['orderby'] );
2852                                 $q['orderby'] = addslashes_gpc( $q['orderby'] );
2853
2854                                 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
2855                                         $parsed = $this->parse_orderby( $orderby );
2856                                         // Only allow certain values for safety.
2857                                         if ( ! $parsed ) {
2858                                                 continue;
2859                                         }
2860
2861                                         $orderby_array[] = $parsed;
2862                                 }
2863                                 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
2864
2865                                 if ( empty( $orderby ) ) {
2866                                         $orderby = "$wpdb->posts.post_date " . $q['order'];
2867                                 } elseif ( ! empty( $q['order'] ) ) {
2868                                         $orderby .= " {$q['order']}";
2869                                 }
2870                         }
2871                 }
2872
2873                 // Order search results by relevance only when another "orderby" is not specified in the query.
2874                 if ( ! empty( $q['s'] ) ) {
2875                         $search_orderby = '';
2876                         if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
2877                                 $search_orderby = $this->parse_search_order( $q );
2878
2879                         /**
2880                          * Filter the ORDER BY used when ordering search results.
2881                          *
2882                          * @since 3.7.0
2883                          *
2884                          * @param string   $search_orderby The ORDER BY clause.
2885                          * @param WP_Query $this           The current WP_Query instance.
2886                          */
2887                         $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
2888                         if ( $search_orderby )
2889                                 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
2890                 }
2891
2892                 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
2893                         $post_type_cap = 'multiple_post_type';
2894                 } else {
2895                         if ( is_array( $post_type ) )
2896                                 $post_type = reset( $post_type );
2897                         $post_type_object = get_post_type_object( $post_type );
2898                         if ( empty( $post_type_object ) )
2899                                 $post_type_cap = $post_type;
2900                 }
2901
2902                 if ( isset( $q['post_password'] ) ) {
2903                         $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
2904                         if ( empty( $q['perm'] ) ) {
2905                                 $q['perm'] = 'readable';
2906                         }
2907                 } elseif ( isset( $q['has_password'] ) ) {
2908                         $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
2909                 }
2910
2911                 if ( 'any' == $post_type ) {
2912                         $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
2913                         if ( empty( $in_search_post_types ) )
2914                                 $where .= ' AND 1=0 ';
2915                         else
2916                                 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')";
2917                 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
2918                         $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
2919                 } elseif ( ! empty( $post_type ) ) {
2920                         $where .= " AND $wpdb->posts.post_type = '$post_type'";
2921                         $post_type_object = get_post_type_object ( $post_type );
2922                 } elseif ( $this->is_attachment ) {
2923                         $where .= " AND $wpdb->posts.post_type = 'attachment'";
2924                         $post_type_object = get_post_type_object ( 'attachment' );
2925                 } elseif ( $this->is_page ) {
2926                         $where .= " AND $wpdb->posts.post_type = 'page'";
2927                         $post_type_object = get_post_type_object ( 'page' );
2928                 } else {
2929                         $where .= " AND $wpdb->posts.post_type = 'post'";
2930                         $post_type_object = get_post_type_object ( 'post' );
2931                 }
2932
2933                 $edit_cap = 'edit_post';
2934                 $read_cap = 'read_post';
2935
2936                 if ( ! empty( $post_type_object ) ) {
2937                         $edit_others_cap = $post_type_object->cap->edit_others_posts;
2938                         $read_private_cap = $post_type_object->cap->read_private_posts;
2939                 } else {
2940                         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
2941                         $read_private_cap = 'read_private_' . $post_type_cap . 's';
2942                 }
2943
2944                 $user_id = get_current_user_id();
2945
2946                 if ( ! empty( $q['post_status'] ) ) {
2947                         $statuswheres = array();
2948                         $q_status = $q['post_status'];
2949                         if ( ! is_array( $q_status ) )
2950                                 $q_status = explode(',', $q_status);
2951                         $r_status = array();
2952                         $p_status = array();
2953                         $e_status = array();
2954                         if ( in_array( 'any', $q_status ) ) {
2955                                 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
2956                                         if ( ! in_array( $status, $q_status ) ) {
2957                                                 $e_status[] = "$wpdb->posts.post_status <> '$status'";
2958                                         }
2959                                 }
2960                         } else {
2961                                 foreach ( get_post_stati() as $status ) {
2962                                         if ( in_array( $status, $q_status ) ) {
2963                                                 if ( 'private' == $status )
2964                                                         $p_status[] = "$wpdb->posts.post_status = '$status'";
2965                                                 else
2966                                                         $r_status[] = "$wpdb->posts.post_status = '$status'";
2967                                         }
2968                                 }
2969                         }
2970
2971                         if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
2972                                 $r_status = array_merge($r_status, $p_status);
2973                                 unset($p_status);
2974                         }
2975
2976                         if ( !empty($e_status) ) {
2977                                 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
2978                         }
2979                         if ( !empty($r_status) ) {
2980                                 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
2981                                         $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
2982                                 else
2983                                         $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
2984                         }
2985                         if ( !empty($p_status) ) {
2986                                 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
2987                                         $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
2988                                 else
2989                                         $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
2990                         }
2991                         if ( $post_status_join ) {
2992                                 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
2993                                 foreach ( $statuswheres as $index => $statuswhere )
2994                                         $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
2995                         }
2996                         $where_status = implode( ' OR ', $statuswheres );
2997                         if ( ! empty( $where_status ) ) {
2998                                 $where .= " AND ($where_status)";
2999                         }
3000                 } elseif ( !$this->is_singular ) {
3001                         $where .= " AND ($wpdb->posts.post_status = 'publish'";
3002
3003                         // Add public states.
3004                         $public_states = get_post_stati( array('public' => true) );
3005                         foreach ( (array) $public_states as $state ) {
3006                                 if ( 'publish' == $state ) // Publish is hard-coded above.
3007                                         continue;
3008                                 $where .= " OR $wpdb->posts.post_status = '$state'";
3009                         }
3010
3011                         if ( $this->is_admin ) {
3012                                 // Add protected states that should show in the admin all list.
3013                                 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3014                                 foreach ( (array) $admin_all_states as $state )
3015                                         $where .= " OR $wpdb->posts.post_status = '$state'";
3016                         }
3017
3018                         if ( is_user_logged_in() ) {
3019                                 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3020                                 $private_states = get_post_stati( array('private' => true) );
3021                                 foreach ( (array) $private_states as $state )
3022                                         $where .= current_user_can( $read_private_cap ) ? " OR $wpdb->posts.post_status = '$state'" : " OR $wpdb->posts.post_author = $user_id AND $wpdb->posts.post_status = '$state'";
3023                         }
3024
3025                         $where .= ')';
3026                 }
3027
3028                 if ( !empty( $this->meta_query->queries ) ) {
3029                         $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
3030                         $join .= $clauses['join'];
3031                         $where .= $clauses['where'];
3032                 }
3033
3034                 /*
3035                  * Apply filters on where and join prior to paging so that any
3036                  * manipulations to them are reflected in the paging by day queries.
3037                  */
3038                 if ( !$q['suppress_filters'] ) {
3039                         /**
3040                          * Filter the WHERE clause of the query.
3041                          *
3042                          * @since 1.5.0
3043                          *
3044                          * @param string   $where The WHERE clause of the query.
3045                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3046                          */
3047                         $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3048
3049                         /**
3050                          * Filter the JOIN clause of the query.
3051                          *
3052                          * @since 1.5.0
3053                          *
3054                          * @param string   $where The JOIN clause of the query.
3055                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3056                          */
3057                         $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3058                 }
3059
3060                 // Paging
3061                 if ( empty($q['nopaging']) && !$this->is_singular ) {
3062                         $page = absint($q['paged']);
3063                         if ( !$page )
3064                                 $page = 1;
3065
3066                         if ( empty($q['offset']) ) {
3067                                 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3068                         } else { // we're ignoring $page and using 'offset'
3069                                 $q['offset'] = absint($q['offset']);
3070                                 $pgstrt = $q['offset'] . ', ';
3071                         }
3072                         $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3073                 }
3074
3075                 // Comments feeds
3076                 if ( $this->is_comment_feed && ! $this->is_singular ) {
3077                         if ( $this->is_archive || $this->is_search ) {
3078                                 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3079                                 $cwhere = "WHERE comment_approved = '1' $where";
3080                                 $cgroupby = "$wpdb->comments.comment_id";
3081                         } else { // Other non singular e.g. front
3082                                 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3083                                 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
3084                                 $cgroupby = '';
3085                         }
3086
3087                         if ( !$q['suppress_filters'] ) {
3088                                 /**
3089                                  * Filter the JOIN clause of the comments feed query before sending.
3090                                  *
3091                                  * @since 2.2.0
3092                                  *
3093                                  * @param string   $cjoin The JOIN clause of the query.
3094                                  * @param WP_Query &$this The WP_Query instance (passed by reference).
3095                                  */
3096                                 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3097
3098                                 /**
3099                                  * Filter the WHERE clause of the comments feed query before sending.
3100                                  *
3101                                  * @since 2.2.0
3102                                  *
3103                                  * @param string   $cwhere The WHERE clause of the query.
3104                                  * @param WP_Query &$this  The WP_Query instance (passed by reference).
3105                                  */
3106                                 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3107
3108                                 /**
3109                                  * Filter the GROUP BY clause of the comments feed query before sending.
3110                                  *
3111                                  * @since 2.2.0
3112                                  *
3113                                  * @param string   $cgroupby The GROUP BY clause of the query.
3114                                  * @param WP_Query &$this    The WP_Query instance (passed by reference).
3115                                  */
3116                                 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3117
3118                                 /**
3119                                  * Filter the ORDER BY clause of the comments feed query before sending.
3120                                  *
3121                                  * @since 2.8.0
3122                                  *
3123                                  * @param string   $corderby The ORDER BY clause of the query.
3124                                  * @param WP_Query &$this    The WP_Query instance (passed by reference).
3125                                  */
3126                                 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3127
3128                                 /**
3129                                  * Filter the LIMIT clause of the comments feed query before sending.
3130                                  *
3131                                  * @since 2.8.0
3132                                  *
3133                                  * @param string   $climits The JOIN clause of the query.
3134                                  * @param WP_Query &$this   The WP_Query instance (passed by reference).
3135                                  */
3136                                 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3137                         }
3138                         $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3139                         $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3140
3141                         $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3142                         $this->comment_count = count($this->comments);
3143
3144                         $post_ids = array();
3145
3146                         foreach ( $this->comments as $comment )
3147                                 $post_ids[] = (int) $comment->comment_post_ID;
3148
3149                         $post_ids = join(',', $post_ids);
3150                         $join = '';
3151                         if ( $post_ids )
3152                                 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3153                         else
3154                                 $where = "AND 0";
3155                 }
3156
3157                 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3158
3159                 /*
3160                  * Apply post-paging filters on where and join. Only plugins that
3161                  * manipulate paging queries should use these hooks.
3162                  */
3163                 if ( !$q['suppress_filters'] ) {
3164                         /**
3165                          * Filter the WHERE clause of the query.
3166                          *
3167                          * Specifically for manipulating paging queries.
3168                          *
3169                          * @since 1.5.0
3170                          *
3171                          * @param string   $where The WHERE clause of the query.
3172                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3173                          */
3174                         $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3175
3176                         /**
3177                          * Filter the GROUP BY clause of the query.
3178                          *
3179                          * @since 2.0.0
3180                          *
3181                          * @param string   $groupby The GROUP BY clause of the query.
3182                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
3183                          */
3184                         $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3185
3186                         /**
3187                          * Filter the JOIN clause of the query.
3188                          *
3189                          * Specifically for manipulating paging queries.
3190                          *
3191                          * @since 1.5.0
3192                          *
3193                          * @param string   $join  The JOIN clause of the query.
3194                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3195                          */
3196                         $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3197
3198                         /**
3199                          * Filter the ORDER BY clause of the query.
3200                          *
3201                          * @since 1.5.1
3202                          *
3203                          * @param string   $orderby The ORDER BY clause of the query.
3204                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
3205                          */
3206                         $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3207
3208                         /**
3209                          * Filter the DISTINCT clause of the query.
3210                          *
3211                          * @since 2.1.0
3212                          *
3213                          * @param string   $distinct The DISTINCT clause of the query.
3214                          * @param WP_Query &$this    The WP_Query instance (passed by reference).
3215                          */
3216                         $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3217
3218                         /**
3219                          * Filter the LIMIT clause of the query.
3220                          *
3221                          * @since 2.1.0
3222                          *
3223                          * @param string   $limits The LIMIT clause of the query.
3224                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
3225                          */
3226                         $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3227
3228                         /**
3229                          * Filter the SELECT clause of the query.
3230                          *
3231                          * @since 2.1.0
3232                          *
3233                          * @param string   $fields The SELECT clause of the query.
3234                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
3235                          */
3236                         $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3237
3238                         /**
3239                          * Filter all query clauses at once, for convenience.
3240                          *
3241                          * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3242                          * fields (SELECT), and LIMITS clauses.
3243                          *
3244                          * @since 3.1.0
3245                          *
3246                          * @param array    $clauses The list of clauses for the query.
3247                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
3248                          */
3249                         $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3250
3251                         $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3252                         $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3253                         $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3254                         $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3255                         $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3256                         $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3257                         $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3258                 }
3259
3260                 /**
3261                  * Fires to announce the query's current selection parameters.
3262                  *
3263                  * For use by caching plugins.
3264                  *
3265                  * @since 2.3.0
3266                  *
3267                  * @param string $selection The assembled selection query.
3268                  */
3269                 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3270
3271                 /*
3272                  * Filter again for the benefit of caching plugins.
3273                  * Regular plugins should use the hooks above.
3274                  */
3275                 if ( !$q['suppress_filters'] ) {
3276                         /**
3277                          * Filter the WHERE clause of the query.
3278                          *
3279                          * For use by caching plugins.
3280                          *
3281                          * @since 2.5.0
3282                          *
3283                          * @param string   $where The WHERE clause of the query.
3284                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3285                          */
3286                         $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3287
3288                         /**
3289                          * Filter the GROUP BY clause of the query.
3290                          *
3291                          * For use by caching plugins.
3292                          *
3293                          * @since 2.5.0
3294                          *
3295                          * @param string   $groupby The GROUP BY clause of the query.
3296                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
3297                          */
3298                         $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3299
3300                         /**
3301                          * Filter the JOIN clause of the query.
3302                          *
3303                          * For use by caching plugins.
3304                          *
3305                          * @since 2.5.0
3306                          *
3307                          * @param string   $join  The JOIN clause of the query.
3308                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3309                          */
3310                         $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3311
3312                         /**
3313                          * Filter the ORDER BY clause of the query.
3314                          *
3315                          * For use by caching plugins.
3316                          *
3317                          * @since 2.5.0
3318                          *
3319                          * @param string   $orderby The ORDER BY clause of the query.
3320                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
3321                          */
3322                         $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3323
3324                         /**
3325                          * Filter the DISTINCT clause of the query.
3326                          *
3327                          * For use by caching plugins.
3328                          *
3329                          * @since 2.5.0
3330                          *
3331                          * @param string   $distinct The DISTINCT clause of the query.
3332                          * @param WP_Query &$this    The WP_Query instance (passed by reference).
3333                          */
3334                         $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3335
3336                         /**
3337                          * Filter the SELECT clause of the query.
3338                          *
3339                          * For use by caching plugins.
3340                          *
3341                          * @since 2.5.0
3342                          *
3343                          * @param string   $fields The SELECT clause of the query.
3344                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
3345                          */
3346                         $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3347
3348                         /**
3349                          * Filter the LIMIT clause of the query.
3350                          *
3351                          * For use by caching plugins.
3352                          *
3353                          * @since 2.5.0
3354                          *
3355                          * @param string   $limits The LIMIT clause of the query.
3356                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
3357                          */
3358                         $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3359
3360                         /**
3361                          * Filter all query clauses at once, for convenience.
3362                          *
3363                          * For use by caching plugins.
3364                          *
3365                          * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3366                          * fields (SELECT), and LIMITS clauses.
3367                          *
3368                          * @since 3.1.0
3369                          *
3370                          * @param array    $pieces The pieces of the query.
3371                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
3372                          */
3373                         $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3374
3375                         $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3376                         $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3377                         $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3378                         $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3379                         $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3380                         $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3381                         $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3382                 }
3383
3384                 if ( ! empty($groupby) )
3385                         $groupby = 'GROUP BY ' . $groupby;
3386                 if ( !empty( $orderby ) )
3387                         $orderby = 'ORDER BY ' . $orderby;
3388
3389                 $found_rows = '';
3390                 if ( !$q['no_found_rows'] && !empty($limits) )
3391                         $found_rows = 'SQL_CALC_FOUND_ROWS';
3392
3393                 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3394
3395                 if ( !$q['suppress_filters'] ) {
3396                         /**
3397                          * Filter the completed SQL query before sending.
3398                          *
3399                          * @since 2.0.0
3400                          *
3401                          * @param array    $request The complete SQL query.
3402                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
3403                          */
3404                         $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3405                 }
3406
3407                 if ( 'ids' == $q['fields'] ) {
3408                         $this->posts = $wpdb->get_col( $this->request );
3409                         $this->post_count = count( $this->posts );
3410                         $this->set_found_posts( $q, $limits );
3411
3412                         return array_map( 'intval', $this->posts );
3413                 }
3414
3415                 if ( 'id=>parent' == $q['fields'] ) {
3416                         $this->posts = $wpdb->get_results( $this->request );
3417                         $this->post_count = count( $this->posts );
3418                         $this->set_found_posts( $q, $limits );
3419
3420                         $r = array();
3421                         foreach ( $this->posts as $post ) {
3422                                 $r[ (int) $post->ID ] = (int) $post->post_parent;
3423                         }
3424                         return $r;
3425                 }
3426
3427                 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3428
3429                 /**
3430                  * Filter whether to split the query.
3431                  *
3432                  * Splitting the query will cause it to fetch just the IDs of the found posts
3433                  * (and then individually fetch each post by ID), rather than fetching every
3434                  * complete row at once. One massive result vs. many small results.
3435                  *
3436                  * @since 3.4.0
3437                  *
3438                  * @param bool     $split_the_query Whether or not to split the query.
3439                  * @param WP_Query $this            The WP_Query instance.
3440                  */
3441                 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3442
3443                 if ( $split_the_query ) {
3444                         // First get the IDs and then fill in the objects
3445
3446                         $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3447
3448                         /**
3449                          * Filter the Post IDs SQL request before sending.
3450                          *
3451                          * @since 3.4.0
3452                          *
3453                          * @param string   $request The post ID request.
3454                          * @param WP_Query $this    The WP_Query instance.
3455                          */
3456                         $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3457
3458                         $ids = $wpdb->get_col( $this->request );
3459
3460                         if ( $ids ) {
3461                                 $this->posts = $ids;
3462                                 $this->set_found_posts( $q, $limits );
3463                                 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3464                         } else {
3465                                 $this->posts = array();
3466                         }
3467                 } else {
3468                         $this->posts = $wpdb->get_results( $this->request );
3469                         $this->set_found_posts( $q, $limits );
3470                 }
3471
3472                 // Convert to WP_Post objects
3473                 if ( $this->posts )
3474                         $this->posts = array_map( 'get_post', $this->posts );
3475
3476                 if ( ! $q['suppress_filters'] ) {
3477                         /**
3478                          * Filter the raw post results array, prior to status checks.
3479                          *
3480                          * @since 2.3.0
3481                          *
3482                          * @param array    $posts The post results array.
3483                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3484                          */
3485                         $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3486                 }
3487
3488                 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3489                         /** This filter is documented in wp-includes/query.php */
3490                         $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3491
3492                         /** This filter is documented in wp-includes/query.php */
3493                         $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3494
3495                         /** This filter is documented in wp-includes/query.php */
3496                         $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3497                         $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3498
3499                         /** This filter is documented in wp-includes/query.php */
3500                         $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3501                         $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3502
3503                         /** This filter is documented in wp-includes/query.php */
3504                         $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3505
3506                         $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3507                         $this->comments = $wpdb->get_results($comments_request);
3508                         $this->comment_count = count($this->comments);
3509                 }
3510
3511                 // Check post status to determine if post should be displayed.
3512                 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3513                         $status = get_post_status($this->posts[0]);
3514                         $post_status_obj = get_post_status_object($status);
3515                         //$type = get_post_type($this->posts[0]);
3516                         if ( !$post_status_obj->public ) {
3517                                 if ( ! is_user_logged_in() ) {
3518                                         // User must be logged in to view unpublished posts.
3519                                         $this->posts = array();
3520                                 } else {
3521                                         if  ( $post_status_obj->protected ) {
3522                                                 // User must have edit permissions on the draft to preview.
3523                                                 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3524                                                         $this->posts = array();
3525                                                 } else {
3526                                                         $this->is_preview = true;
3527                                                         if ( 'future' != $status )
3528                                                                 $this->posts[0]->post_date = current_time('mysql');
3529                                                 }
3530                                         } elseif ( $post_status_obj->private ) {
3531                                                 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3532                                                         $this->posts = array();
3533                                         } else {
3534                                                 $this->posts = array();
3535                                         }
3536                                 }
3537                         }
3538
3539                         if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3540                                 /**
3541                                  * Filter the single post for preview mode.
3542                                  *
3543                                  * @since 2.7.0
3544                                  *
3545                                  * @param WP_Post  $post_preview  The Post object.
3546                                  * @param WP_Query &$this         The WP_Query instance (passed by reference).
3547                                  */
3548                                 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3549                         }
3550                 }
3551
3552                 // Put sticky posts at the top of the posts array
3553                 $sticky_posts = get_option('sticky_posts');
3554                 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3555                         $num_posts = count($this->posts);
3556                         $sticky_offset = 0;
3557                         // Loop over posts and relocate stickies to the front.
3558                         for ( $i = 0; $i < $num_posts; $i++ ) {
3559                                 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3560                                         $sticky_post = $this->posts[$i];
3561                                         // Remove sticky from current position
3562                                         array_splice($this->posts, $i, 1);
3563                                         // Move to front, after other stickies
3564                                         array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3565                                         // Increment the sticky offset. The next sticky will be placed at this offset.
3566                                         $sticky_offset++;
3567                                         // Remove post from sticky posts array
3568                                         $offset = array_search($sticky_post->ID, $sticky_posts);
3569                                         unset( $sticky_posts[$offset] );
3570                                 }
3571                         }
3572
3573                         // If any posts have been excluded specifically, Ignore those that are sticky.
3574                         if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3575                                 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3576
3577                         // Fetch sticky posts that weren't in the query results
3578                         if ( !empty($sticky_posts) ) {
3579                                 $stickies = get_posts( array(
3580                                         'post__in' => $sticky_posts,
3581                                         'post_type' => $post_type,
3582                                         'post_status' => 'publish',
3583                                         'nopaging' => true
3584                                 ) );
3585
3586                                 foreach ( $stickies as $sticky_post ) {
3587                                         array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3588                                         $sticky_offset++;
3589                                 }
3590                         }
3591                 }
3592
3593                 if ( ! $q['suppress_filters'] ) {
3594                         /**
3595                          * Filter the array of retrieved posts after they've been fetched and
3596                          * internally processed.
3597                          *
3598                          * @since 1.5.0
3599                          *
3600                          * @param array    $posts The array of retrieved posts.
3601                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3602                          */
3603                         $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3604                 }
3605
3606                 // Ensure that any posts added/modified via one of the filters above are
3607                 // of the type WP_Post and are filtered.
3608                 if ( $this->posts ) {
3609                         $this->post_count = count( $this->posts );
3610
3611                         $this->posts = array_map( 'get_post', $this->posts );
3612
3613                         if ( $q['cache_results'] )
3614                                 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3615
3616                         $this->post = reset( $this->posts );
3617                 } else {
3618                         $this->post_count = 0;
3619                         $this->posts = array();
3620                 }
3621
3622                 return $this->posts;
3623         }
3624
3625         /**
3626          * Set up the amount of found posts and the number of pages (if limit clause was used)
3627          * for the current query.
3628          *
3629          * @since 3.5.0
3630          * @access private
3631          */
3632         private function set_found_posts( $q, $limits ) {
3633                 global $wpdb;
3634
3635                 // Bail if posts is an empty array. Continue if posts is an empty string,
3636                 // null, or false to accommodate caching plugins that fill posts later.
3637                 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3638                         return;
3639
3640                 if ( ! empty( $limits ) ) {
3641                         /**
3642                          * Filter the query to run for retrieving the found posts.
3643                          *
3644                          * @since 2.1.0
3645                          *
3646                          * @param string   $found_posts The query to run to find the found posts.
3647                          * @param WP_Query &$this       The WP_Query instance (passed by reference).
3648                          */
3649                         $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3650                 } else {
3651                         $this->found_posts = count( $this->posts );
3652                 }
3653
3654                 /**
3655                  * Filter the number of found posts for the query.
3656                  *
3657                  * @since 2.1.0
3658                  *
3659                  * @param int      $found_posts The number of posts found.
3660                  * @param WP_Query &$this       The WP_Query instance (passed by reference).
3661                  */
3662                 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3663
3664                 if ( ! empty( $limits ) )
3665                         $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3666         }
3667
3668         /**
3669          * Set up the next post and iterate current post index.
3670          *
3671          * @since 1.5.0
3672          * @access public
3673          *
3674          * @return WP_Post Next post.
3675          */
3676         public function next_post() {
3677
3678                 $this->current_post++;
3679
3680                 $this->post = $this->posts[$this->current_post];
3681                 return $this->post;
3682         }
3683
3684         /**
3685          * Sets up the current post.
3686          *
3687          * Retrieves the next post, sets up the post, sets the 'in the loop'
3688          * property to true.
3689          *
3690          * @since 1.5.0
3691          * @access public
3692          */
3693         public function the_post() {
3694                 global $post;
3695                 $this->in_the_loop = true;
3696
3697                 if ( $this->current_post == -1 ) // loop has just started
3698                         /**
3699                          * Fires once the loop is started.
3700                          *
3701                          * @since 2.0.0
3702                          *
3703                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3704                          */
3705                         do_action_ref_array( 'loop_start', array( &$this ) );
3706
3707                 $post = $this->next_post();
3708                 $this->setup_postdata( $post );
3709         }
3710
3711         /**
3712          * Whether there are more posts available in the loop.
3713          *
3714          * Calls action 'loop_end', when the loop is complete.
3715          *
3716          * @since 1.5.0
3717          * @access public
3718          *
3719          * @return bool True if posts are available, false if end of loop.
3720          */
3721         public function have_posts() {
3722                 if ( $this->current_post + 1 < $this->post_count ) {
3723                         return true;
3724                 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3725                         /**
3726                          * Fires once the loop has ended.
3727                          *
3728                          * @since 2.0.0
3729                          *
3730                          * @param WP_Query &$this The WP_Query instance (passed by reference).
3731                          */
3732                         do_action_ref_array( 'loop_end', array( &$this ) );
3733                         // Do some cleaning up after the loop
3734                         $this->rewind_posts();
3735                 }
3736
3737                 $this->in_the_loop = false;
3738                 return false;
3739         }
3740
3741         /**
3742          * Rewind the posts and reset post index.
3743          *
3744          * @since 1.5.0
3745          * @access public
3746          */
3747         public function rewind_posts() {
3748                 $this->current_post = -1;
3749                 if ( $this->post_count > 0 ) {
3750                         $this->post = $this->posts[0];
3751                 }
3752         }
3753
3754         /**
3755          * Iterate current comment index and return comment object.
3756          *
3757          * @since 2.2.0
3758          * @access public
3759          *
3760          * @return object Comment object.
3761          */
3762         public function next_comment() {
3763                 $this->current_comment++;
3764
3765                 $this->comment = $this->comments[$this->current_comment];
3766                 return $this->comment;
3767         }
3768
3769         /**
3770          * Sets up the current comment.
3771          *
3772          * @since 2.2.0
3773          * @access public
3774          * @global object $comment Current comment.
3775          */
3776         public function the_comment() {
3777                 global $comment;
3778
3779                 $comment = $this->next_comment();
3780
3781                 if ( $this->current_comment == 0 ) {
3782                         /**
3783                          * Fires once the comment loop is started.
3784                          *
3785                          * @since 2.2.0
3786                          */
3787                         do_action( 'comment_loop_start' );
3788                 }
3789         }
3790
3791         /**
3792          * Whether there are more comments available.
3793          *
3794          * Automatically rewinds comments when finished.
3795          *
3796          * @since 2.2.0
3797          * @access public
3798          *
3799          * @return bool True, if more comments. False, if no more posts.
3800          */
3801         public function have_comments() {
3802                 if ( $this->current_comment + 1 < $this->comment_count ) {
3803                         return true;
3804                 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
3805                         $this->rewind_comments();
3806                 }
3807
3808                 return false;
3809         }
3810
3811         /**
3812          * Rewind the comments, resets the comment index and comment to first.
3813          *
3814          * @since 2.2.0
3815          * @access public
3816          */
3817         public function rewind_comments() {
3818                 $this->current_comment = -1;
3819                 if ( $this->comment_count > 0 ) {
3820                         $this->comment = $this->comments[0];
3821                 }
3822         }
3823
3824         /**
3825          * Sets up the WordPress query by parsing query string.
3826          *
3827          * @since 1.5.0
3828          * @access public
3829          *
3830          * @param string $query URL query string.
3831          * @return array List of posts.
3832          */
3833         public function query( $query ) {
3834                 $this->init();
3835                 $this->query = $this->query_vars = wp_parse_args( $query );
3836                 return $this->get_posts();
3837         }
3838
3839         /**
3840          * Retrieve queried object.
3841          *
3842          * If queried object is not set, then the queried object will be set from
3843          * the category, tag, taxonomy, posts page, single post, page, or author
3844          * query variable. After it is set up, it will be returned.
3845          *
3846          * @since 1.5.0
3847          * @access public
3848          *
3849          * @return object
3850          */
3851         public function get_queried_object() {
3852                 if ( isset($this->queried_object) )
3853                         return $this->queried_object;
3854
3855                 $this->queried_object = null;
3856                 $this->queried_object_id = 0;
3857
3858                 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
3859                         if ( $this->is_category ) {
3860                                 if ( $this->get( 'cat' ) ) {
3861                                         $term = get_term( $this->get( 'cat' ), 'category' );
3862                                 } elseif ( $this->get( 'category_name' ) ) {
3863                                         $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
3864                                 }
3865                         } elseif ( $this->is_tag ) {
3866                                 if ( $this->get( 'tag_id' ) ) {
3867                                         $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
3868                                 } elseif ( $this->get( 'tag' ) ) {
3869                                         $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
3870                                 }
3871                         } else {
3872                                 // For other tax queries, grab the first term from the first clause.
3873                                 $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' );
3874
3875                                 $queried_taxonomies = array_keys( $tax_query_in_and );
3876                                 $matched_taxonomy = reset( $queried_taxonomies );
3877                                 $query = $tax_query_in_and[ $matched_taxonomy ];
3878
3879                                 if ( $query['terms'] ) {
3880                                         if ( 'term_id' == $query['field'] ) {
3881                                                 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
3882                                         } else {
3883                                                 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
3884                                         }
3885                                 }
3886                         }
3887
3888                         if ( ! empty( $term ) && ! is_wp_error( $term ) )  {
3889                                 $this->queried_object = $term;
3890                                 $this->queried_object_id = (int) $term->term_id;
3891
3892                                 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
3893                                         _make_cat_compat( $this->queried_object );
3894                         }
3895                 } elseif ( $this->is_post_type_archive ) {
3896                         $post_type = $this->get( 'post_type' );
3897                         if ( is_array( $post_type ) )
3898                                 $post_type = reset( $post_type );
3899                         $this->queried_object = get_post_type_object( $post_type );
3900                 } elseif ( $this->is_posts_page ) {
3901                         $page_for_posts = get_option('page_for_posts');
3902                         $this->queried_object = get_post( $page_for_posts );
3903                         $this->queried_object_id = (int) $this->queried_object->ID;
3904                 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
3905                         $this->queried_object = $this->post;
3906                         $this->queried_object_id = (int) $this->post->ID;
3907                 } elseif ( $this->is_author ) {
3908                         $this->queried_object_id = (int) $this->get('author');
3909                         $this->queried_object = get_userdata( $this->queried_object_id );
3910                 }
3911
3912                 return $this->queried_object;
3913         }
3914
3915         /**
3916          * Retrieve ID of the current queried object.
3917          *
3918          * @since 1.5.0
3919          * @access public
3920          *
3921          * @return int
3922          */
3923         public function get_queried_object_id() {
3924                 $this->get_queried_object();
3925
3926                 if ( isset($this->queried_object_id) ) {
3927                         return $this->queried_object_id;
3928                 }
3929
3930                 return 0;
3931         }
3932
3933         /**
3934          * Constructor.
3935          *
3936          * Sets up the WordPress query, if parameter is not empty.
3937          *
3938          * @since 1.5.0
3939          * @access public
3940          *
3941          * @param string $query URL query string.
3942          * @return WP_Query
3943          */
3944         public function __construct($query = '') {
3945                 if ( ! empty($query) ) {
3946                         $this->query($query);
3947                 }
3948         }
3949
3950         /**
3951          * Make private properties readable for backwards compatibility.
3952          *
3953          * @since 4.0.0
3954          * @access public
3955          *
3956          * @param string $name Property to get.
3957          * @return mixed Property.
3958          */
3959         public function __get( $name ) {
3960                 return $this->$name;
3961         }
3962
3963         /**
3964          * Make private properties settable for backwards compatibility.
3965          *
3966          * @since 4.0.0
3967          * @access public
3968          *
3969          * @param string $name Property to check if set.
3970          * @return bool Whether the property is set.
3971          */
3972         public function __isset( $name ) {
3973                 return isset( $this->$name );
3974         }
3975
3976         /**
3977          * Make private properties settable for backwards compatibility.
3978          *
3979          * @since 4.0.0
3980          * @access public
3981          *
3982          * @param string $name Property to unset.
3983          */
3984         public function __unset( $name ) {
3985                 unset( $this->$name );
3986         }
3987
3988         /**
3989          * Make private/protected methods readable for backwards compatibility.
3990          *
3991          * @since 4.0.0
3992          * @access public
3993          *
3994          * @param callable $name      Method to call.
3995          * @param array    $arguments Arguments to pass when calling.
3996          * @return mixed|bool Return value of the callback, otherwise false.
3997          */
3998         public function __call( $name, $arguments ) {
3999                 return call_user_func_array( array( $this, $name ), $arguments );
4000         }
4001
4002         /**
4003          * Is the query for an existing archive page?
4004          *
4005          * Month, Year, Category, Author, Post Type archive...
4006          *
4007          * @since 3.1.0
4008          *
4009          * @return bool
4010          */
4011         public function is_archive() {
4012                 return (bool) $this->is_archive;
4013         }
4014
4015         /**
4016          * Is the query for an existing post type archive page?
4017          *
4018          * @since 3.1.0
4019          *
4020          * @param mixed $post_types Optional. Post type or array of posts types to check against.
4021          * @return bool
4022          */
4023         public function is_post_type_archive( $post_types = '' ) {
4024                 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4025                         return (bool) $this->is_post_type_archive;
4026
4027                 $post_type = $this->get( 'post_type' );
4028                 if ( is_array( $post_type ) )
4029                         $post_type = reset( $post_type );
4030                 $post_type_object = get_post_type_object( $post_type );
4031
4032                 return in_array( $post_type_object->name, (array) $post_types );
4033         }
4034
4035         /**
4036          * Is the query for an existing attachment page?
4037          *
4038          * @since 3.1.0
4039          *
4040          * @param mixed $attachment Attachment ID, title, slug, or array of such.
4041          * @return bool
4042          */
4043         public function is_attachment( $attachment = '' ) {
4044                 if ( ! $this->is_attachment ) {
4045                         return false;
4046                 }
4047
4048                 if ( empty( $attachment ) ) {
4049                         return true;
4050                 }
4051
4052                 $attachment = (array) $attachment;
4053
4054                 $post_obj = $this->get_queried_object();
4055
4056                 if ( in_array( $post_obj->ID, $attachment ) ) {
4057                         return true;
4058                 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4059                         return true;
4060                 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4061                         return true;
4062                 }
4063                 return false;
4064         }
4065
4066         /**
4067          * Is the query for an existing author archive page?
4068          *
4069          * If the $author parameter is specified, this function will additionally
4070          * check if the query is for one of the authors specified.
4071          *
4072          * @since 3.1.0
4073          *
4074          * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4075          * @return bool
4076          */
4077         public function is_author( $author = '' ) {
4078                 if ( !$this->is_author )
4079                         return false;
4080
4081                 if ( empty($author) )
4082                         return true;
4083
4084                 $author_obj = $this->get_queried_object();
4085
4086                 $author = (array) $author;
4087
4088                 if ( in_array( $author_obj->ID, $author ) )
4089                         return true;
4090                 elseif ( in_array( $author_obj->nickname, $author ) )
4091                         return true;
4092                 elseif ( in_array( $author_obj->user_nicename, $author ) )
4093                         return true;
4094
4095                 return false;
4096         }
4097
4098         /**
4099          * Is the query for an existing category archive page?
4100          *
4101          * If the $category parameter is specified, this function will additionally
4102          * check if the query is for one of the categories specified.
4103          *
4104          * @since 3.1.0
4105          *
4106          * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4107          * @return bool
4108          */
4109         public function is_category( $category = '' ) {
4110                 if ( !$this->is_category )
4111                         return false;
4112
4113                 if ( empty($category) )
4114                         return true;
4115
4116                 $cat_obj = $this->get_queried_object();
4117
4118                 $category = (array) $category;
4119
4120                 if ( in_array( $cat_obj->term_id, $category ) )
4121                         return true;
4122                 elseif ( in_array( $cat_obj->name, $category ) )
4123                         return true;
4124                 elseif ( in_array( $cat_obj->slug, $category ) )
4125                         return true;
4126
4127                 return false;
4128         }
4129
4130         /**
4131          * Is the query for an existing tag archive page?
4132          *
4133          * If the $tag parameter is specified, this function will additionally
4134          * check if the query is for one of the tags specified.
4135          *
4136          * @since 3.1.0
4137          *
4138          * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4139          * @return bool
4140          */
4141         public function is_tag( $tag = '' ) {
4142                 if ( ! $this->is_tag )
4143                         return false;
4144
4145                 if ( empty( $tag ) )
4146                         return true;
4147
4148                 $tag_obj = $this->get_queried_object();
4149
4150                 $tag = (array) $tag;
4151
4152                 if ( in_array( $tag_obj->term_id, $tag ) )
4153                         return true;
4154                 elseif ( in_array( $tag_obj->name, $tag ) )
4155                         return true;
4156                 elseif ( in_array( $tag_obj->slug, $tag ) )
4157                         return true;
4158
4159                 return false;
4160         }
4161
4162         /**
4163          * Is the query for an existing taxonomy archive page?
4164          *
4165          * If the $taxonomy parameter is specified, this function will additionally
4166          * check if the query is for that specific $taxonomy.
4167          *
4168          * If the $term parameter is specified in addition to the $taxonomy parameter,
4169          * this function will additionally check if the query is for one of the terms
4170          * specified.
4171          *
4172          * @since 3.1.0
4173          *
4174          * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4175          * @param mixed $term. Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4176          * @return bool
4177          */
4178         public function is_tax( $taxonomy = '', $term = '' ) {
4179                 global $wp_taxonomies;
4180
4181                 if ( !$this->is_tax )
4182                         return false;
4183
4184                 if ( empty( $taxonomy ) )
4185                         return true;
4186
4187                 $queried_object = $this->get_queried_object();
4188                 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4189                 $term_array = (array) $term;
4190
4191                 // Check that the taxonomy matches.
4192                 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4193                         return false;
4194
4195                 // Only a Taxonomy provided.
4196                 if ( empty( $term ) )
4197                         return true;
4198
4199                 return isset( $queried_object->term_id ) &&
4200                         count( array_intersect(
4201                                 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4202                                 $term_array
4203                         ) );
4204         }
4205
4206         /**
4207          * Whether the current URL is within the comments popup window.
4208          *
4209          * @since 3.1.0
4210          *
4211          * @return bool
4212          */
4213         public function is_comments_popup() {
4214                 return (bool) $this->is_comments_popup;
4215         }
4216
4217         /**
4218          * Is the query for an existing date archive?
4219          *
4220          * @since 3.1.0
4221          *
4222          * @return bool
4223          */
4224         public function is_date() {
4225                 return (bool) $this->is_date;
4226         }
4227
4228         /**
4229          * Is the query for an existing day archive?
4230          *
4231          * @since 3.1.0
4232          *
4233          * @return bool
4234          */
4235         public function is_day() {
4236                 return (bool) $this->is_day;
4237         }
4238
4239         /**
4240          * Is the query for a feed?
4241          *
4242          * @since 3.1.0
4243          *
4244          * @param string|array $feeds Optional feed types to check.
4245          * @return bool
4246          */
4247         public function is_feed( $feeds = '' ) {
4248                 if ( empty( $feeds ) || ! $this->is_feed )
4249                         return (bool) $this->is_feed;
4250                 $qv = $this->get( 'feed' );
4251                 if ( 'feed' == $qv )
4252                         $qv = get_default_feed();
4253                 return in_array( $qv, (array) $feeds );
4254         }
4255
4256         /**
4257          * Is the query for a comments feed?
4258          *
4259          * @since 3.1.0
4260          *
4261          * @return bool
4262          */
4263         public function is_comment_feed() {
4264                 return (bool) $this->is_comment_feed;
4265         }
4266
4267         /**
4268          * Is the query for the front page of the site?
4269          *
4270          * This is for what is displayed at your site's main URL.
4271          *
4272          * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4273          *
4274          * If you set a static page for the front page of your site, this function will return
4275          * true when viewing that page.
4276          *
4277          * Otherwise the same as @see WP_Query::is_home()
4278          *
4279          * @since 3.1.0
4280          *
4281          * @return bool True, if front of site.
4282          */
4283         public function is_front_page() {
4284                 // most likely case
4285                 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4286                         return true;
4287                 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4288                         return true;
4289                 else
4290                         return false;
4291         }
4292
4293         /**
4294          * Is the query for the blog homepage?
4295          *
4296          * This is the page which shows the time based blog content of your site.
4297          *
4298          * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4299          *
4300          * If you set a static page for the front page of your site, this function will return
4301          * true only on the page you set as the "Posts page".
4302          *
4303          * @see WP_Query::is_front_page()
4304          *
4305          * @since 3.1.0
4306          *
4307          * @return bool True if blog view homepage.
4308          */
4309         public function is_home() {
4310                 return (bool) $this->is_home;
4311         }
4312
4313         /**
4314          * Is the query for an existing month archive?
4315          *
4316          * @since 3.1.0
4317          *
4318          * @return bool
4319          */
4320         public function is_month() {
4321                 return (bool) $this->is_month;
4322         }
4323
4324         /**
4325          * Is the query for an existing single page?
4326          *
4327          * If the $page parameter is specified, this function will additionally
4328          * check if the query is for one of the pages specified.
4329          *
4330          * @see WP_Query::is_single()
4331          * @see WP_Query::is_singular()
4332          *
4333          * @since 3.1.0
4334          *
4335          * @param mixed $page Page ID, title, slug, path, or array of such.
4336          * @return bool
4337          */
4338         public function is_page( $page = '' ) {
4339                 if ( !$this->is_page )
4340                         return false;
4341
4342                 if ( empty( $page ) )
4343                         return true;
4344
4345                 $page_obj = $this->get_queried_object();
4346
4347                 $page = (array) $page;
4348
4349                 if ( in_array( $page_obj->ID, $page ) ) {
4350                         return true;
4351                 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4352                         return true;
4353                 } else if ( in_array( $page_obj->post_name, $page ) ) {
4354                         return true;
4355                 } else {
4356                         foreach ( $page as $pagepath ) {
4357                                 if ( ! strpos( $pagepath, '/' ) ) {
4358                                         continue;
4359                                 }
4360                                 $pagepath_obj = get_page_by_path( $pagepath );
4361
4362                                 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4363                                         return true;
4364                                 }
4365                         }
4366                 }
4367
4368                 return false;
4369         }
4370
4371         /**
4372          * Is the query for paged result and not for the first page?
4373          *
4374          * @since 3.1.0
4375          *
4376          * @return bool
4377          */
4378         public function is_paged() {
4379                 return (bool) $this->is_paged;
4380         }
4381
4382         /**
4383          * Is the query for a post or page preview?
4384          *
4385          * @since 3.1.0
4386          *
4387          * @return bool
4388          */
4389         public function is_preview() {
4390                 return (bool) $this->is_preview;
4391         }
4392
4393         /**
4394          * Is the query for the robots file?
4395          *
4396          * @since 3.1.0
4397          *
4398          * @return bool
4399          */
4400         public function is_robots() {
4401                 return (bool) $this->is_robots;
4402         }
4403
4404         /**
4405          * Is the query for a search?
4406          *
4407          * @since 3.1.0
4408          *
4409          * @return bool
4410          */
4411         public function is_search() {
4412                 return (bool) $this->is_search;
4413         }
4414
4415         /**
4416          * Is the query for an existing single post?
4417          *
4418          * Works for any post type, except attachments and pages
4419          *
4420          * If the $post parameter is specified, this function will additionally
4421          * check if the query is for one of the Posts specified.
4422          *
4423          * @see WP_Query::is_page()
4424          * @see WP_Query::is_singular()
4425          *
4426          * @since 3.1.0
4427          *
4428          * @param mixed $post Post ID, title, slug, path, or array of such.
4429          * @return bool
4430          */
4431         public function is_single( $post = '' ) {
4432                 if ( !$this->is_single )
4433                         return false;
4434
4435                 if ( empty($post) )
4436                         return true;
4437
4438                 $post_obj = $this->get_queried_object();
4439
4440                 $post = (array) $post;
4441
4442                 if ( in_array( $post_obj->ID, $post ) ) {
4443                         return true;
4444                 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4445                         return true;
4446                 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4447                         return true;
4448                 } else {
4449                         foreach ( $post as $postpath ) {
4450                                 if ( ! strpos( $postpath, '/' ) ) {
4451                                         continue;
4452                                 }
4453                                 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4454
4455                                 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4456                                         return true;
4457                                 }
4458                         }
4459                 }
4460                 return false;
4461         }
4462
4463         /**
4464          * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4465          *
4466          * If the $post_types parameter is specified, this function will additionally
4467          * check if the query is for one of the Posts Types specified.
4468          *
4469          * @see WP_Query::is_page()
4470          * @see WP_Query::is_single()
4471          *
4472          * @since 3.1.0
4473          *
4474          * @param mixed $post_types Optional. Post Type or array of Post Types
4475          * @return bool
4476          */
4477         public function is_singular( $post_types = '' ) {
4478                 if ( empty( $post_types ) || !$this->is_singular )
4479                         return (bool) $this->is_singular;
4480
4481                 $post_obj = $this->get_queried_object();
4482
4483                 return in_array( $post_obj->post_type, (array) $post_types );
4484         }
4485
4486         /**
4487          * Is the query for a specific time?
4488          *
4489          * @since 3.1.0
4490          *
4491          * @return bool
4492          */
4493         public function is_time() {
4494                 return (bool) $this->is_time;
4495         }
4496
4497         /**
4498          * Is the query for a trackback endpoint call?
4499          *
4500          * @since 3.1.0
4501          *
4502          * @return bool
4503          */
4504         public function is_trackback() {
4505                 return (bool) $this->is_trackback;
4506         }
4507
4508         /**
4509          * Is the query for an existing year archive?
4510          *
4511          * @since 3.1.0
4512          *
4513          * @return bool
4514          */
4515         public function is_year() {
4516                 return (bool) $this->is_year;
4517         }
4518
4519         /**
4520          * Is the query a 404 (returns no results)?
4521          *
4522          * @since 3.1.0
4523          *
4524          * @return bool
4525          */
4526         public function is_404() {
4527                 return (bool) $this->is_404;
4528         }
4529
4530         /**
4531          * Is the query the main query?
4532          *
4533          * @since 3.3.0
4534          *
4535          * @return bool
4536          */
4537         public function is_main_query() {
4538                 global $wp_the_query;
4539                 return $wp_the_query === $this;
4540         }
4541
4542         /**
4543          * Set up global post data.
4544          *
4545          * @since 4.1.0
4546          *
4547          * @param WP_Post $post Post data.
4548          * @return bool True when finished.
4549          */
4550         public function setup_postdata( $post ) {
4551                 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4552
4553                 $id = (int) $post->ID;
4554
4555                 $authordata = get_userdata($post->post_author);
4556
4557                 $currentday = mysql2date('d.m.y', $post->post_date, false);
4558                 $currentmonth = mysql2date('m', $post->post_date, false);
4559                 $numpages = 1;
4560                 $multipage = 0;
4561                 $page = $this->get( 'page' );
4562                 if ( ! $page )
4563                         $page = 1;
4564
4565                 /*
4566                  * Force full post content when viewing the permalink for the $post,
4567                  * or when on an RSS feed. Otherwise respect the 'more' tag.
4568                  */
4569                 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4570                         $more = 1;
4571                 } else if ( $this->is_feed() ) {
4572                         $more = 1;
4573                 } else {
4574                         $more = 0;
4575                 }
4576
4577                 $content = $post->post_content;
4578                 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4579                         if ( $page > 1 )
4580                                 $more = 1;
4581                         $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4582                         $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4583                         $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4584
4585                         // Ignore nextpage at the beginning of the content.
4586                         if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4587                                 $content = substr( $content, 15 );
4588
4589                         $pages = explode('<!--nextpage-->', $content);
4590                         $numpages = count($pages);
4591                         if ( $numpages > 1 )
4592                                 $multipage = 1;
4593                 } else {
4594                         $pages = array( $post->post_content );
4595                 }
4596
4597                 /**
4598                  * Fires once the post data has been setup.
4599                  *
4600                  * @since 2.8.0
4601                  * @since 4.1.0 Introduced `$this` parameter.
4602                  *
4603                  * @param WP_Post  &$post The Post object (passed by reference).
4604                  * @param WP_Query &$this The current Query object (passed by reference).
4605                  */
4606                 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4607
4608                 return true;
4609         }
4610         /**
4611          * After looping through a nested query, this function
4612          * restores the $post global to the current post in this query.
4613          *
4614          * @since 3.7.0
4615          */
4616         public function reset_postdata() {
4617                 if ( ! empty( $this->post ) ) {
4618                         $GLOBALS['post'] = $this->post;
4619                         setup_postdata( $this->post );
4620                 }
4621         }
4622 }
4623
4624 /**
4625  * Redirect old slugs to the correct permalink.
4626  *
4627  * Attempts to find the current slug from the past slugs.
4628  *
4629  * @since 2.1.0
4630  *
4631  * @uses $wp_query
4632  * @global wpdb $wpdb WordPress database abstraction object.
4633  *
4634  * @return null If no link is found, null is returned.
4635  */
4636 function wp_old_slug_redirect() {
4637         global $wp_query;
4638         if ( is_404() && '' != $wp_query->query_vars['name'] ) :
4639                 global $wpdb;
4640
4641                 // Guess the current post_type based on the query vars.
4642                 if ( get_query_var('post_type') )
4643                         $post_type = get_query_var('post_type');
4644                 elseif ( !empty($wp_query->query_vars['pagename']) )
4645                         $post_type = 'page';
4646                 else
4647                         $post_type = 'post';
4648
4649                 if ( is_array( $post_type ) ) {
4650                         if ( count( $post_type ) > 1 )
4651                                 return;
4652                         $post_type = array_shift( $post_type );
4653                 }
4654
4655                 // Do not attempt redirect for hierarchical post types
4656                 if ( is_post_type_hierarchical( $post_type ) )
4657                         return;
4658
4659                 $query = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND post_type = %s AND meta_key = '_wp_old_slug' AND meta_value = %s", $post_type, $wp_query->query_vars['name']);
4660
4661                 // if year, monthnum, or day have been specified, make our query more precise
4662                 // just in case there are multiple identical _wp_old_slug values
4663                 if ( '' != $wp_query->query_vars['year'] )
4664                         $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
4665                 if ( '' != $wp_query->query_vars['monthnum'] )
4666                         $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
4667                 if ( '' != $wp_query->query_vars['day'] )
4668                         $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
4669
4670                 $id = (int) $wpdb->get_var($query);
4671
4672                 if ( ! $id )
4673                         return;
4674
4675                 $link = get_permalink($id);
4676
4677                 if ( !$link )
4678                         return;
4679
4680                 wp_redirect( $link, 301 ); // Permanent redirect
4681                 exit;
4682         endif;
4683 }
4684
4685 /**
4686  * Set up global post data.
4687  *
4688  * @since 1.5.0
4689  *
4690  * @param object $post Post data.
4691  * @return bool True when finished.
4692  */
4693 function setup_postdata( $post ) {
4694         global $wp_query;
4695
4696         if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
4697                 return $wp_query->setup_postdata( $post );
4698         }
4699
4700         return false;
4701 }