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