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