WordPress 4.7.2
[autoinstalls/wordpress.git] / wp-includes / class-wp-query.php
1 <?php
2 /**
3  * Query API: WP_Query class
4  *
5  * @package WordPress
6  * @subpackage Query
7  * @since 4.7.0
8  */
9
10 /**
11  * The WordPress Query class.
12  *
13  * @link https://codex.wordpress.org/Function_Reference/WP_Query Codex page.
14  *
15  * @since 1.5.0
16  * @since 4.5.0 Removed the `$comments_popup` property.
17  */
18 class WP_Query {
19
20         /**
21          * Query vars set by the user
22          *
23          * @since 1.5.0
24          * @access public
25          * @var array
26          */
27         public $query;
28
29         /**
30          * Query vars, after parsing
31          *
32          * @since 1.5.0
33          * @access public
34          * @var array
35          */
36         public $query_vars = array();
37
38         /**
39          * Taxonomy query, as passed to get_tax_sql()
40          *
41          * @since 3.1.0
42          * @access public
43          * @var object WP_Tax_Query
44          */
45         public $tax_query;
46
47         /**
48          * Metadata query container
49          *
50          * @since 3.2.0
51          * @access public
52          * @var object WP_Meta_Query
53          */
54         public $meta_query = false;
55
56         /**
57          * Date query container
58          *
59          * @since 3.7.0
60          * @access public
61          * @var object WP_Date_Query
62          */
63         public $date_query = false;
64
65         /**
66          * Holds the data for a single object that is queried.
67          *
68          * Holds the contents of a post, page, category, attachment.
69          *
70          * @since 1.5.0
71          * @access public
72          * @var object|array
73          */
74         public $queried_object;
75
76         /**
77          * The ID of the queried object.
78          *
79          * @since 1.5.0
80          * @access public
81          * @var int
82          */
83         public $queried_object_id;
84
85         /**
86          * Get post database query.
87          *
88          * @since 2.0.1
89          * @access public
90          * @var string
91          */
92         public $request;
93
94         /**
95          * List of posts.
96          *
97          * @since 1.5.0
98          * @access public
99          * @var array
100          */
101         public $posts;
102
103         /**
104          * The amount of posts for the current query.
105          *
106          * @since 1.5.0
107          * @access public
108          * @var int
109          */
110         public $post_count = 0;
111
112         /**
113          * Index of the current item in the loop.
114          *
115          * @since 1.5.0
116          * @access public
117          * @var int
118          */
119         public $current_post = -1;
120
121         /**
122          * Whether the loop has started and the caller is in the loop.
123          *
124          * @since 2.0.0
125          * @access public
126          * @var bool
127          */
128         public $in_the_loop = false;
129
130         /**
131          * The current post.
132          *
133          * @since 1.5.0
134          * @access public
135          * @var WP_Post
136          */
137         public $post;
138
139         /**
140          * The list of comments for current post.
141          *
142          * @since 2.2.0
143          * @access public
144          * @var array
145          */
146         public $comments;
147
148         /**
149          * The amount of comments for the posts.
150          *
151          * @since 2.2.0
152          * @access public
153          * @var int
154          */
155         public $comment_count = 0;
156
157         /**
158          * The index of the comment in the comment loop.
159          *
160          * @since 2.2.0
161          * @access public
162          * @var int
163          */
164         public $current_comment = -1;
165
166         /**
167          * Current comment ID.
168          *
169          * @since 2.2.0
170          * @access public
171          * @var int
172          */
173         public $comment;
174
175         /**
176          * The amount of found posts for the current query.
177          *
178          * If limit clause was not used, equals $post_count.
179          *
180          * @since 2.1.0
181          * @access public
182          * @var int
183          */
184         public $found_posts = 0;
185
186         /**
187          * The amount of pages.
188          *
189          * @since 2.1.0
190          * @access public
191          * @var int
192          */
193         public $max_num_pages = 0;
194
195         /**
196          * The amount of comment pages.
197          *
198          * @since 2.7.0
199          * @access public
200          * @var int
201          */
202         public $max_num_comment_pages = 0;
203
204         /**
205          * Set if query is single post.
206          *
207          * @since 1.5.0
208          * @access public
209          * @var bool
210          */
211         public $is_single = false;
212
213         /**
214          * Set if query is preview of blog.
215          *
216          * @since 2.0.0
217          * @access public
218          * @var bool
219          */
220         public $is_preview = false;
221
222         /**
223          * Set if query returns a page.
224          *
225          * @since 1.5.0
226          * @access public
227          * @var bool
228          */
229         public $is_page = false;
230
231         /**
232          * Set if query is an archive list.
233          *
234          * @since 1.5.0
235          * @access public
236          * @var bool
237          */
238         public $is_archive = false;
239
240         /**
241          * Set if query is part of a date.
242          *
243          * @since 1.5.0
244          * @access public
245          * @var bool
246          */
247         public $is_date = false;
248
249         /**
250          * Set if query contains a year.
251          *
252          * @since 1.5.0
253          * @access public
254          * @var bool
255          */
256         public $is_year = false;
257
258         /**
259          * Set if query contains a month.
260          *
261          * @since 1.5.0
262          * @access public
263          * @var bool
264          */
265         public $is_month = false;
266
267         /**
268          * Set if query contains a day.
269          *
270          * @since 1.5.0
271          * @access public
272          * @var bool
273          */
274         public $is_day = false;
275
276         /**
277          * Set if query contains time.
278          *
279          * @since 1.5.0
280          * @access public
281          * @var bool
282          */
283         public $is_time = false;
284
285         /**
286          * Set if query contains an author.
287          *
288          * @since 1.5.0
289          * @access public
290          * @var bool
291          */
292         public $is_author = false;
293
294         /**
295          * Set if query contains category.
296          *
297          * @since 1.5.0
298          * @access public
299          * @var bool
300          */
301         public $is_category = false;
302
303         /**
304          * Set if query contains tag.
305          *
306          * @since 2.3.0
307          * @access public
308          * @var bool
309          */
310         public $is_tag = false;
311
312         /**
313          * Set if query contains taxonomy.
314          *
315          * @since 2.5.0
316          * @access public
317          * @var bool
318          */
319         public $is_tax = false;
320
321         /**
322          * Set if query was part of a search result.
323          *
324          * @since 1.5.0
325          * @access public
326          * @var bool
327          */
328         public $is_search = false;
329
330         /**
331          * Set if query is feed display.
332          *
333          * @since 1.5.0
334          * @access public
335          * @var bool
336          */
337         public $is_feed = false;
338
339         /**
340          * Set if query is comment feed display.
341          *
342          * @since 2.2.0
343          * @access public
344          * @var bool
345          */
346         public $is_comment_feed = false;
347
348         /**
349          * Set if query is trackback.
350          *
351          * @since 1.5.0
352          * @access public
353          * @var bool
354          */
355         public $is_trackback = false;
356
357         /**
358          * Set if query is blog homepage.
359          *
360          * @since 1.5.0
361          * @access public
362          * @var bool
363          */
364         public $is_home = false;
365
366         /**
367          * Set if query couldn't found anything.
368          *
369          * @since 1.5.0
370          * @access public
371          * @var bool
372          */
373         public $is_404 = false;
374
375         /**
376          * Set if query is embed.
377          *
378          * @since 4.4.0
379          * @access public
380          * @var bool
381          */
382         public $is_embed = false;
383
384         /**
385          * Set if query is paged
386          *
387          * @since 1.5.0
388          * @access public
389          * @var bool
390          */
391         public $is_paged = false;
392
393         /**
394          * Set if query is part of administration page.
395          *
396          * @since 1.5.0
397          * @access public
398          * @var bool
399          */
400         public $is_admin = false;
401
402         /**
403          * Set if query is an attachment.
404          *
405          * @since 2.0.0
406          * @access public
407          * @var bool
408          */
409         public $is_attachment = false;
410
411         /**
412          * Set if is single, is a page, or is an attachment.
413          *
414          * @since 2.1.0
415          * @access public
416          * @var bool
417          */
418         public $is_singular = false;
419
420         /**
421          * Set if query is for robots.
422          *
423          * @since 2.1.0
424          * @access public
425          * @var bool
426          */
427         public $is_robots = false;
428
429         /**
430          * Set if query contains posts.
431          *
432          * Basically, the homepage if the option isn't set for the static homepage.
433          *
434          * @since 2.1.0
435          * @access public
436          * @var bool
437          */
438         public $is_posts_page = false;
439
440         /**
441          * Set if query is for a post type archive.
442          *
443          * @since 3.1.0
444          * @access public
445          * @var bool
446          */
447         public $is_post_type_archive = false;
448
449         /**
450          * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
451          * whether we have to re-parse because something has changed
452          *
453          * @since 3.1.0
454          * @access private
455          * @var bool|string
456          */
457         private $query_vars_hash = false;
458
459         /**
460          * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
461          * via pre_get_posts hooks.
462          *
463          * @since 3.1.1
464          * @access private
465          */
466         private $query_vars_changed = true;
467
468         /**
469          * Set if post thumbnails are cached
470          *
471          * @since 3.2.0
472          * @access public
473          * @var bool
474          */
475          public $thumbnails_cached = false;
476
477         /**
478          * Cached list of search stopwords.
479          *
480          * @since 3.7.0
481          * @var array
482          */
483         private $stopwords;
484
485         private $compat_fields = array( 'query_vars_hash', 'query_vars_changed' );
486
487         private $compat_methods = array( 'init_query_flags', 'parse_tax_query' );
488
489         /**
490          * Resets query flags to false.
491          *
492          * The query flags are what page info WordPress was able to figure out.
493          *
494          * @since 2.0.0
495          * @access private
496          */
497         private function init_query_flags() {
498                 $this->is_single = false;
499                 $this->is_preview = false;
500                 $this->is_page = false;
501                 $this->is_archive = false;
502                 $this->is_date = false;
503                 $this->is_year = false;
504                 $this->is_month = false;
505                 $this->is_day = false;
506                 $this->is_time = false;
507                 $this->is_author = false;
508                 $this->is_category = false;
509                 $this->is_tag = false;
510                 $this->is_tax = false;
511                 $this->is_search = false;
512                 $this->is_feed = false;
513                 $this->is_comment_feed = false;
514                 $this->is_trackback = false;
515                 $this->is_home = false;
516                 $this->is_404 = false;
517                 $this->is_paged = false;
518                 $this->is_admin = false;
519                 $this->is_attachment = false;
520                 $this->is_singular = false;
521                 $this->is_robots = false;
522                 $this->is_posts_page = false;
523                 $this->is_post_type_archive = false;
524         }
525
526         /**
527          * Initiates object properties and sets default values.
528          *
529          * @since 1.5.0
530          * @access public
531          */
532         public function init() {
533                 unset($this->posts);
534                 unset($this->query);
535                 $this->query_vars = array();
536                 unset($this->queried_object);
537                 unset($this->queried_object_id);
538                 $this->post_count = 0;
539                 $this->current_post = -1;
540                 $this->in_the_loop = false;
541                 unset( $this->request );
542                 unset( $this->post );
543                 unset( $this->comments );
544                 unset( $this->comment );
545                 $this->comment_count = 0;
546                 $this->current_comment = -1;
547                 $this->found_posts = 0;
548                 $this->max_num_pages = 0;
549                 $this->max_num_comment_pages = 0;
550
551                 $this->init_query_flags();
552         }
553
554         /**
555          * Reparse the query vars.
556          *
557          * @since 1.5.0
558          * @access public
559          */
560         public function parse_query_vars() {
561                 $this->parse_query();
562         }
563
564         /**
565          * Fills in the query variables, which do not exist within the parameter.
566          *
567          * @since 2.1.0
568          * @since 4.4.0 Removed the `comments_popup` public query variable.
569          * @access public
570          *
571          * @param array $array Defined query variables.
572          * @return array Complete query variables with undefined ones filled in empty.
573          */
574         public function fill_query_vars($array) {
575                 $keys = array(
576                         'error'
577                         , 'm'
578                         , 'p'
579                         , 'post_parent'
580                         , 'subpost'
581                         , 'subpost_id'
582                         , 'attachment'
583                         , 'attachment_id'
584                         , 'name'
585                         , 'static'
586                         , 'pagename'
587                         , 'page_id'
588                         , 'second'
589                         , 'minute'
590                         , 'hour'
591                         , 'day'
592                         , 'monthnum'
593                         , 'year'
594                         , 'w'
595                         , 'category_name'
596                         , 'tag'
597                         , 'cat'
598                         , 'tag_id'
599                         , 'author'
600                         , 'author_name'
601                         , 'feed'
602                         , 'tb'
603                         , 'paged'
604                         , 'meta_key'
605                         , 'meta_value'
606                         , 'preview'
607                         , 's'
608                         , 'sentence'
609                         , 'title'
610                         , 'fields'
611                         , 'menu_order'
612                         , 'embed'
613                 );
614
615                 foreach ( $keys as $key ) {
616                         if ( !isset($array[$key]) )
617                                 $array[$key] = '';
618                 }
619
620                 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in', 'post_name__in',
621                         'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
622                         'author__in', 'author__not_in' );
623
624                 foreach ( $array_keys as $key ) {
625                         if ( !isset($array[$key]) )
626                                 $array[$key] = array();
627                 }
628                 return $array;
629         }
630
631         /**
632          * Parse a query string and set query type booleans.
633          *
634          * @since 1.5.0
635          * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
636          *              array key to `$orderby`.
637          * @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
638          *              search terms, by prepending a hyphen.
639          * @since 4.5.0 Removed the `$comments_popup` parameter.
640          *              Introduced the `$comment_status` and `$ping_status` parameters.
641          *              Introduced `RAND(x)` syntax for `$orderby`, which allows an integer seed value to random sorts.
642          * @since 4.6.0 Added 'post_name__in' support for `$orderby`. Introduced the `$lazy_load_term_meta` argument.
643          * @access public
644          *
645          * @param string|array $query {
646          *     Optional. Array or string of Query parameters.
647          *
648          *     @type int          $attachment_id           Attachment post ID. Used for 'attachment' post_type.
649          *     @type int|string   $author                  Author ID, or comma-separated list of IDs.
650          *     @type string       $author_name             User 'user_nicename'.
651          *     @type array        $author__in              An array of author IDs to query from.
652          *     @type array        $author__not_in          An array of author IDs not to query from.
653          *     @type bool         $cache_results           Whether to cache post information. Default true.
654          *     @type int|string   $cat                     Category ID or comma-separated list of IDs (this or any children).
655          *     @type array        $category__and           An array of category IDs (AND in).
656          *     @type array        $category__in            An array of category IDs (OR in, no children).
657          *     @type array        $category__not_in        An array of category IDs (NOT in).
658          *     @type string       $category_name           Use category slug (not name, this or any children).
659          *     @type string       $comment_status          Comment status.
660          *     @type int          $comments_per_page       The number of comments to return per page.
661          *                                                 Default 'comments_per_page' option.
662          *     @type array        $date_query              An associative array of WP_Date_Query arguments.
663          *                                                 See WP_Date_Query::__construct().
664          *     @type int          $day                     Day of the month. Default empty. Accepts numbers 1-31.
665          *     @type bool         $exact                   Whether to search by exact keyword. Default false.
666          *     @type string|array $fields                  Which fields to return. Single field or all fields (string),
667          *                                                 or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
668          *                                                 Default all fields. Accepts 'ids', 'id=>parent'.
669          *     @type int          $hour                    Hour of the day. Default empty. Accepts numbers 0-23.
670          *     @type int|bool     $ignore_sticky_posts     Whether to ignore sticky posts or not. Setting this to false
671          *                                                 excludes stickies from 'post__in'. Accepts 1|true, 0|false.
672          *                                                 Default 0|false.
673          *     @type int          $m                       Combination YearMonth. Accepts any four-digit year and month
674          *                                                 numbers 1-12. Default empty.
675          *     @type string       $meta_compare            Comparison operator to test the 'meta_value'.
676          *     @type string       $meta_key                Custom field key.
677          *     @type array        $meta_query              An associative array of WP_Meta_Query arguments. See WP_Meta_Query.
678          *     @type string       $meta_value              Custom field value.
679          *     @type int          $meta_value_num          Custom field value number.
680          *     @type int          $menu_order              The menu order of the posts.
681          *     @type int          $monthnum                The two-digit month. Default empty. Accepts numbers 1-12.
682          *     @type string       $name                    Post slug.
683          *     @type bool         $nopaging                Show all posts (true) or paginate (false). Default false.
684          *     @type bool         $no_found_rows           Whether to skip counting the total rows found. Enabling can improve
685          *                                                 performance. Default false.
686          *     @type int          $offset                  The number of posts to offset before retrieval.
687          *     @type string       $order                   Designates ascending or descending order of posts. Default 'DESC'.
688          *                                                 Accepts 'ASC', 'DESC'.
689          *     @type string|array $orderby                 Sort retrieved posts by parameter. One or more options may be
690          *                                                 passed. To use 'meta_value', or 'meta_value_num',
691          *                                                 'meta_key=keyname' must be also be defined. To sort by a
692          *                                                 specific `$meta_query` clause, use that clause's array key.
693          *                                                 Default 'date'. Accepts 'none', 'name', 'author', 'date',
694          *                                                 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand',
695          *                                                 'RAND(x)' (where 'x' is an integer seed value),
696          *                                                 'comment_count', 'meta_value', 'meta_value_num', 'post__in',
697          *                                                 'post_name__in', 'post_parent__in', and the array keys
698          *                                                 of `$meta_query`.
699          *     @type int          $p                       Post ID.
700          *     @type int          $page                    Show the number of posts that would show up on page X of a
701          *                                                 static front page.
702          *     @type int          $paged                   The number of the current page.
703          *     @type int          $page_id                 Page ID.
704          *     @type string       $pagename                Page slug.
705          *     @type string       $perm                    Show posts if user has the appropriate capability.
706          *     @type string       $ping_status             Ping status.
707          *     @type array        $post__in                An array of post IDs to retrieve, sticky posts will be included
708          *     @type string       $post_mime_type          The mime type of the post. Used for 'attachment' post_type.
709          *     @type array        $post__not_in            An array of post IDs not to retrieve. Note: a string of comma-
710          *                                                 separated IDs will NOT work.
711          *     @type int          $post_parent             Page ID to retrieve child pages for. Use 0 to only retrieve
712          *                                                 top-level pages.
713          *     @type array        $post_parent__in         An array containing parent page IDs to query child pages from.
714          *     @type array        $post_parent__not_in     An array containing parent page IDs not to query child pages from.
715          *     @type string|array $post_type               A post type slug (string) or array of post type slugs.
716          *                                                 Default 'any' if using 'tax_query'.
717          *     @type string|array $post_status             A post status (string) or array of post statuses.
718          *     @type int          $posts_per_page          The number of posts to query for. Use -1 to request all posts.
719          *     @type int          $posts_per_archive_page  The number of posts to query for by archive page. Overrides
720          *                                                 'posts_per_page' when is_archive(), or is_search() are true.
721          *     @type array        $post_name__in           An array of post slugs that results must match.
722          *     @type string       $s                       Search keyword(s). Prepending a term with a hyphen will
723          *                                                 exclude posts matching that term. Eg, 'pillow -sofa' will
724          *                                                 return posts containing 'pillow' but not 'sofa'. The
725          *                                                 character used for exclusion can be modified using the
726          *                                                 the 'wp_query_search_exclusion_prefix' filter.
727          *     @type int          $second                  Second of the minute. Default empty. Accepts numbers 0-60.
728          *     @type bool         $sentence                Whether to search by phrase. Default false.
729          *     @type bool         $suppress_filters        Whether to suppress filters. Default false.
730          *     @type string       $tag                     Tag slug. Comma-separated (either), Plus-separated (all).
731          *     @type array        $tag__and                An array of tag ids (AND in).
732          *     @type array        $tag__in                 An array of tag ids (OR in).
733          *     @type array        $tag__not_in             An array of tag ids (NOT in).
734          *     @type int          $tag_id                  Tag id or comma-separated list of IDs.
735          *     @type array        $tag_slug__and           An array of tag slugs (AND in).
736          *     @type array        $tag_slug__in            An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
737          *                                                 true. Note: a string of comma-separated IDs will NOT work.
738          *     @type array        $tax_query               An associative array of WP_Tax_Query arguments.
739          *                                                 See WP_Tax_Query->queries.
740          *     @type string       $title                   Post title.
741          *     @type bool         $update_post_meta_cache  Whether to update the post meta cache. Default true.
742          *     @type bool         $update_post_term_cache  Whether to update the post term cache. Default true.
743          *     @type bool         $lazy_load_term_meta     Whether to lazy-load term meta. Setting to false will
744          *                                                 disable cache priming for term meta, so that each
745          *                                                 get_term_meta() call will hit the database.
746          *                                                 Defaults to the value of `$update_post_term_cache`.
747          *     @type int          $w                       The week number of the year. Default empty. Accepts numbers 0-53.
748          *     @type int          $year                    The four-digit year. Default empty. Accepts any four-digit year.
749          * }
750          */
751         public function parse_query( $query =  '' ) {
752                 if ( ! empty( $query ) ) {
753                         $this->init();
754                         $this->query = $this->query_vars = wp_parse_args( $query );
755                 } elseif ( ! isset( $this->query ) ) {
756                         $this->query = $this->query_vars;
757                 }
758
759                 $this->query_vars = $this->fill_query_vars($this->query_vars);
760                 $qv = &$this->query_vars;
761                 $this->query_vars_changed = true;
762
763                 if ( ! empty($qv['robots']) )
764                         $this->is_robots = true;
765
766                 if ( ! is_scalar( $qv['p'] ) || $qv['p'] < 0 ) {
767                         $qv['p'] = 0;
768                         $qv['error'] = '404';
769                 } else {
770                         $qv['p'] = intval( $qv['p'] );
771                 }
772
773                 $qv['page_id'] =  absint($qv['page_id']);
774                 $qv['year'] = absint($qv['year']);
775                 $qv['monthnum'] = absint($qv['monthnum']);
776                 $qv['day'] = absint($qv['day']);
777                 $qv['w'] = absint($qv['w']);
778                 $qv['m'] = is_scalar( $qv['m'] ) ? preg_replace( '|[^0-9]|', '', $qv['m'] ) : '';
779                 $qv['paged'] = absint($qv['paged']);
780                 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
781                 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
782                 $qv['pagename'] = trim( $qv['pagename'] );
783                 $qv['name'] = trim( $qv['name'] );
784                 $qv['title'] = trim( $qv['title'] );
785                 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
786                 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
787                 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
788                 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
789
790                 // Fairly insane upper bound for search string lengths.
791                 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
792                         $qv['s'] = '';
793                 }
794
795                 // Compat. Map subpost to attachment.
796                 if ( '' != $qv['subpost'] )
797                         $qv['attachment'] = $qv['subpost'];
798                 if ( '' != $qv['subpost_id'] )
799                         $qv['attachment_id'] = $qv['subpost_id'];
800
801                 $qv['attachment_id'] = absint($qv['attachment_id']);
802
803                 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
804                         $this->is_single = true;
805                         $this->is_attachment = true;
806                 } elseif ( '' != $qv['name'] ) {
807                         $this->is_single = true;
808                 } elseif ( $qv['p'] ) {
809                         $this->is_single = true;
810                 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
811                         // If year, month, day, hour, minute, and second are set, a single
812                         // post is being queried.
813                         $this->is_single = true;
814                 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
815                         $this->is_page = true;
816                         $this->is_single = false;
817                 } else {
818                         // Look for archive queries. Dates, categories, authors, search, post type archives.
819
820                         if ( isset( $this->query['s'] ) ) {
821                                 $this->is_search = true;
822                         }
823
824                         if ( '' !== $qv['second'] ) {
825                                 $this->is_time = true;
826                                 $this->is_date = true;
827                         }
828
829                         if ( '' !== $qv['minute'] ) {
830                                 $this->is_time = true;
831                                 $this->is_date = true;
832                         }
833
834                         if ( '' !== $qv['hour'] ) {
835                                 $this->is_time = true;
836                                 $this->is_date = true;
837                         }
838
839                         if ( $qv['day'] ) {
840                                 if ( ! $this->is_date ) {
841                                         $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
842                                         if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
843                                                 $qv['error'] = '404';
844                                         } else {
845                                                 $this->is_day = true;
846                                                 $this->is_date = true;
847                                         }
848                                 }
849                         }
850
851                         if ( $qv['monthnum'] ) {
852                                 if ( ! $this->is_date ) {
853                                         if ( 12 < $qv['monthnum'] ) {
854                                                 $qv['error'] = '404';
855                                         } else {
856                                                 $this->is_month = true;
857                                                 $this->is_date = true;
858                                         }
859                                 }
860                         }
861
862                         if ( $qv['year'] ) {
863                                 if ( ! $this->is_date ) {
864                                         $this->is_year = true;
865                                         $this->is_date = true;
866                                 }
867                         }
868
869                         if ( $qv['m'] ) {
870                                 $this->is_date = true;
871                                 if ( strlen($qv['m']) > 9 ) {
872                                         $this->is_time = true;
873                                 } elseif ( strlen( $qv['m'] ) > 7 ) {
874                                         $this->is_day = true;
875                                 } elseif ( strlen( $qv['m'] ) > 5 ) {
876                                         $this->is_month = true;
877                                 } else {
878                                         $this->is_year = true;
879                                 }
880                         }
881
882                         if ( '' != $qv['w'] ) {
883                                 $this->is_date = true;
884                         }
885
886                         $this->query_vars_hash = false;
887                         $this->parse_tax_query( $qv );
888
889                         foreach ( $this->tax_query->queries as $tax_query ) {
890                                 if ( ! is_array( $tax_query ) ) {
891                                         continue;
892                                 }
893
894                                 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
895                                         switch ( $tax_query['taxonomy'] ) {
896                                                 case 'category':
897                                                         $this->is_category = true;
898                                                         break;
899                                                 case 'post_tag':
900                                                         $this->is_tag = true;
901                                                         break;
902                                                 default:
903                                                         $this->is_tax = true;
904                                         }
905                                 }
906                         }
907                         unset( $tax_query );
908
909                         if ( empty($qv['author']) || ($qv['author'] == '0') ) {
910                                 $this->is_author = false;
911                         } else {
912                                 $this->is_author = true;
913                         }
914
915                         if ( '' != $qv['author_name'] )
916                                 $this->is_author = true;
917
918                         if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
919                                 $post_type_obj = get_post_type_object( $qv['post_type'] );
920                                 if ( ! empty( $post_type_obj->has_archive ) )
921                                         $this->is_post_type_archive = true;
922                         }
923
924                         if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
925                                 $this->is_archive = true;
926                 }
927
928                 if ( '' != $qv['feed'] )
929                         $this->is_feed = true;
930
931                 if ( '' != $qv['embed'] ) {
932                         $this->is_embed = true;
933                 }
934
935                 if ( '' != $qv['tb'] )
936                         $this->is_trackback = true;
937
938                 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
939                         $this->is_paged = true;
940
941                 // if we're previewing inside the write screen
942                 if ( '' != $qv['preview'] )
943                         $this->is_preview = true;
944
945                 if ( is_admin() )
946                         $this->is_admin = true;
947
948                 if ( false !== strpos($qv['feed'], 'comments-') ) {
949                         $qv['feed'] = str_replace('comments-', '', $qv['feed']);
950                         $qv['withcomments'] = 1;
951                 }
952
953                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
954
955                 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
956                         $this->is_comment_feed = true;
957
958                 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_robots ) )
959                         $this->is_home = true;
960
961                 // Correct is_* for page_on_front and page_for_posts
962                 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
963                         $_query = wp_parse_args($this->query);
964                         // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
965                         if ( isset($_query['pagename']) && '' == $_query['pagename'] )
966                                 unset($_query['pagename']);
967
968                         unset( $_query['embed'] );
969
970                         if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
971                                 $this->is_page = true;
972                                 $this->is_home = false;
973                                 $qv['page_id'] = get_option('page_on_front');
974                                 // Correct <!--nextpage--> for page_on_front
975                                 if ( !empty($qv['paged']) ) {
976                                         $qv['page'] = $qv['paged'];
977                                         unset($qv['paged']);
978                                 }
979                         }
980                 }
981
982                 if ( '' != $qv['pagename'] ) {
983                         $this->queried_object = get_page_by_path( $qv['pagename'] );
984
985                         if ( $this->queried_object && 'attachment' == $this->queried_object->post_type ) {
986                                 if ( preg_match( "/^[^%]*%(?:postname)%/", get_option( 'permalink_structure' ) ) ) {
987                                         // See if we also have a post with the same slug
988                                         $post = get_page_by_path( $qv['pagename'], OBJECT, 'post' );
989                                         if ( $post ) {
990                                                 $this->queried_object = $post;
991                                                 $this->is_page = false;
992                                                 $this->is_single = true;
993                                         }
994                                 }
995                         }
996
997                         if ( ! empty( $this->queried_object ) ) {
998                                 $this->queried_object_id = (int) $this->queried_object->ID;
999                         } else {
1000                                 unset( $this->queried_object );
1001                         }
1002
1003                         if  ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1004                                 $this->is_page = false;
1005                                 $this->is_home = true;
1006                                 $this->is_posts_page = true;
1007                         }
1008                 }
1009
1010                 if ( $qv['page_id'] ) {
1011                         if  ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1012                                 $this->is_page = false;
1013                                 $this->is_home = true;
1014                                 $this->is_posts_page = true;
1015                         }
1016                 }
1017
1018                 if ( !empty($qv['post_type']) ) {
1019                         if ( is_array($qv['post_type']) )
1020                                 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1021                         else
1022                                 $qv['post_type'] = sanitize_key($qv['post_type']);
1023                 }
1024
1025                 if ( ! empty( $qv['post_status'] ) ) {
1026                         if ( is_array( $qv['post_status'] ) )
1027                                 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1028                         else
1029                                 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1030                 }
1031
1032                 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1033                         $this->is_comment_feed = false;
1034
1035                 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1036                 // Done correcting is_* for page_on_front and page_for_posts
1037
1038                 if ( '404' == $qv['error'] )
1039                         $this->set_404();
1040
1041                 $this->is_embed = $this->is_embed && ( $this->is_singular || $this->is_404 );
1042
1043                 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1044                 $this->query_vars_changed = false;
1045
1046                 /**
1047                  * Fires after the main query vars have been parsed.
1048                  *
1049                  * @since 1.5.0
1050                  *
1051                  * @param WP_Query &$this The WP_Query instance (passed by reference).
1052                  */
1053                 do_action_ref_array( 'parse_query', array( &$this ) );
1054         }
1055
1056         /**
1057          * Parses various taxonomy related query vars.
1058          *
1059          * For BC, this method is not marked as protected. See [28987].
1060          *
1061          * @access protected
1062          * @since 3.1.0
1063          *
1064          * @param array $q The query variables. Passed by reference.
1065          */
1066         public function parse_tax_query( &$q ) {
1067                 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1068                         $tax_query = $q['tax_query'];
1069                 } else {
1070                         $tax_query = array();
1071                 }
1072
1073                 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1074                         $tax_query[] = array(
1075                                 'taxonomy' => $q['taxonomy'],
1076                                 'terms' => array( $q['term'] ),
1077                                 'field' => 'slug',
1078                         );
1079                 }
1080
1081                 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1082                         if ( 'post_tag' == $taxonomy )
1083                                 continue;       // Handled further down in the $q['tag'] block
1084
1085                         if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1086                                 $tax_query_defaults = array(
1087                                         'taxonomy' => $taxonomy,
1088                                         'field' => 'slug',
1089                                 );
1090
1091                                 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1092                                         $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1093                                 }
1094
1095                                 $term = $q[$t->query_var];
1096
1097                                 if ( is_array( $term ) ) {
1098                                         $term = implode( ',', $term );
1099                                 }
1100
1101                                 if ( strpos($term, '+') !== false ) {
1102                                         $terms = preg_split( '/[+]+/', $term );
1103                                         foreach ( $terms as $term ) {
1104                                                 $tax_query[] = array_merge( $tax_query_defaults, array(
1105                                                         'terms' => array( $term )
1106                                                 ) );
1107                                         }
1108                                 } else {
1109                                         $tax_query[] = array_merge( $tax_query_defaults, array(
1110                                                 'terms' => preg_split( '/[,]+/', $term )
1111                                         ) );
1112                                 }
1113                         }
1114                 }
1115
1116                 // If querystring 'cat' is an array, implode it.
1117                 if ( is_array( $q['cat'] ) ) {
1118                         $q['cat'] = implode( ',', $q['cat'] );
1119                 }
1120
1121                 // Category stuff
1122                 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1123                         $cat_in = $cat_not_in = array();
1124
1125                         $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1126                         $cat_array = array_map( 'intval', $cat_array );
1127                         $q['cat'] = implode( ',', $cat_array );
1128
1129                         foreach ( $cat_array as $cat ) {
1130                                 if ( $cat > 0 )
1131                                         $cat_in[] = $cat;
1132                                 elseif ( $cat < 0 )
1133                                         $cat_not_in[] = abs( $cat );
1134                         }
1135
1136                         if ( ! empty( $cat_in ) ) {
1137                                 $tax_query[] = array(
1138                                         'taxonomy' => 'category',
1139                                         'terms' => $cat_in,
1140                                         'field' => 'term_id',
1141                                         'include_children' => true
1142                                 );
1143                         }
1144
1145                         if ( ! empty( $cat_not_in ) ) {
1146                                 $tax_query[] = array(
1147                                         'taxonomy' => 'category',
1148                                         'terms' => $cat_not_in,
1149                                         'field' => 'term_id',
1150                                         'operator' => 'NOT IN',
1151                                         'include_children' => true
1152                                 );
1153                         }
1154                         unset( $cat_array, $cat_in, $cat_not_in );
1155                 }
1156
1157                 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1158                         $q['category__and'] = (array) $q['category__and'];
1159                         if ( ! isset( $q['category__in'] ) )
1160                                 $q['category__in'] = array();
1161                         $q['category__in'][] = absint( reset( $q['category__and'] ) );
1162                         unset( $q['category__and'] );
1163                 }
1164
1165                 if ( ! empty( $q['category__in'] ) ) {
1166                         $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1167                         $tax_query[] = array(
1168                                 'taxonomy' => 'category',
1169                                 'terms' => $q['category__in'],
1170                                 'field' => 'term_id',
1171                                 'include_children' => false
1172                         );
1173                 }
1174
1175                 if ( ! empty($q['category__not_in']) ) {
1176                         $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
1177                         $tax_query[] = array(
1178                                 'taxonomy' => 'category',
1179                                 'terms' => $q['category__not_in'],
1180                                 'operator' => 'NOT IN',
1181                                 'include_children' => false
1182                         );
1183                 }
1184
1185                 if ( ! empty($q['category__and']) ) {
1186                         $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
1187                         $tax_query[] = array(
1188                                 'taxonomy' => 'category',
1189                                 'terms' => $q['category__and'],
1190                                 'field' => 'term_id',
1191                                 'operator' => 'AND',
1192                                 'include_children' => false
1193                         );
1194                 }
1195
1196                 // If querystring 'tag' is array, implode it.
1197                 if ( is_array( $q['tag'] ) ) {
1198                         $q['tag'] = implode( ',', $q['tag'] );
1199                 }
1200
1201                 // Tag stuff
1202                 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
1203                         if ( strpos($q['tag'], ',') !== false ) {
1204                                 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
1205                                 foreach ( (array) $tags as $tag ) {
1206                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1207                                         $q['tag_slug__in'][] = $tag;
1208                                 }
1209                         } elseif ( preg_match('/[+\r\n\t ]+/', $q['tag'] ) || ! empty( $q['cat'] ) ) {
1210                                 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
1211                                 foreach ( (array) $tags as $tag ) {
1212                                         $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1213                                         $q['tag_slug__and'][] = $tag;
1214                                 }
1215                         } else {
1216                                 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1217                                 $q['tag_slug__in'][] = $q['tag'];
1218                         }
1219                 }
1220
1221                 if ( !empty($q['tag_id']) ) {
1222                         $q['tag_id'] = absint( $q['tag_id'] );
1223                         $tax_query[] = array(
1224                                 'taxonomy' => 'post_tag',
1225                                 'terms' => $q['tag_id']
1226                         );
1227                 }
1228
1229                 if ( !empty($q['tag__in']) ) {
1230                         $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
1231                         $tax_query[] = array(
1232                                 'taxonomy' => 'post_tag',
1233                                 'terms' => $q['tag__in']
1234                         );
1235                 }
1236
1237                 if ( !empty($q['tag__not_in']) ) {
1238                         $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
1239                         $tax_query[] = array(
1240                                 'taxonomy' => 'post_tag',
1241                                 'terms' => $q['tag__not_in'],
1242                                 'operator' => 'NOT IN'
1243                         );
1244                 }
1245
1246                 if ( !empty($q['tag__and']) ) {
1247                         $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
1248                         $tax_query[] = array(
1249                                 'taxonomy' => 'post_tag',
1250                                 'terms' => $q['tag__and'],
1251                                 'operator' => 'AND'
1252                         );
1253                 }
1254
1255                 if ( !empty($q['tag_slug__in']) ) {
1256                         $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
1257                         $tax_query[] = array(
1258                                 'taxonomy' => 'post_tag',
1259                                 'terms' => $q['tag_slug__in'],
1260                                 'field' => 'slug'
1261                         );
1262                 }
1263
1264                 if ( !empty($q['tag_slug__and']) ) {
1265                         $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
1266                         $tax_query[] = array(
1267                                 'taxonomy' => 'post_tag',
1268                                 'terms' => $q['tag_slug__and'],
1269                                 'field' => 'slug',
1270                                 'operator' => 'AND'
1271                         );
1272                 }
1273
1274                 $this->tax_query = new WP_Tax_Query( $tax_query );
1275
1276                 /**
1277                  * Fires after taxonomy-related query vars have been parsed.
1278                  *
1279                  * @since 3.7.0
1280                  *
1281                  * @param WP_Query $this The WP_Query instance.
1282                  */
1283                 do_action( 'parse_tax_query', $this );
1284         }
1285
1286         /**
1287          * Generate SQL for the WHERE clause based on passed search terms.
1288          *
1289          * @since 3.7.0
1290          *
1291          * @param array $q Query variables.
1292          * @return string WHERE clause.
1293          */
1294         protected function parse_search( &$q ) {
1295                 global $wpdb;
1296
1297                 $search = '';
1298
1299                 // added slashes screw with quote grouping when done early, so done later
1300                 $q['s'] = stripslashes( $q['s'] );
1301                 if ( empty( $_GET['s'] ) && $this->is_main_query() )
1302                         $q['s'] = urldecode( $q['s'] );
1303                 // there are no line breaks in <input /> fields
1304                 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
1305                 $q['search_terms_count'] = 1;
1306                 if ( ! empty( $q['sentence'] ) ) {
1307                         $q['search_terms'] = array( $q['s'] );
1308                 } else {
1309                         if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
1310                                 $q['search_terms_count'] = count( $matches[0] );
1311                                 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
1312                                 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
1313                                 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
1314                                         $q['search_terms'] = array( $q['s'] );
1315                         } else {
1316                                 $q['search_terms'] = array( $q['s'] );
1317                         }
1318                 }
1319
1320                 $n = ! empty( $q['exact'] ) ? '' : '%';
1321                 $searchand = '';
1322                 $q['search_orderby_title'] = array();
1323
1324                 /**
1325                  * Filters the prefix that indicates that a search term should be excluded from results.
1326                  *
1327                  * @since 4.7.0
1328                  *
1329                  * @param string $exclusion_prefix The prefix. Default '-'. Returning
1330                  *                                 an empty value disables exclusions.
1331                  */
1332                 $exclusion_prefix = apply_filters( 'wp_query_search_exclusion_prefix', '-' );
1333
1334                 foreach ( $q['search_terms'] as $term ) {
1335                         // If there is an $exclusion_prefix, terms prefixed with it should be excluded.
1336                         $exclude = $exclusion_prefix && ( $exclusion_prefix === substr( $term, 0, 1 ) );
1337                         if ( $exclude ) {
1338                                 $like_op  = 'NOT LIKE';
1339                                 $andor_op = 'AND';
1340                                 $term     = substr( $term, 1 );
1341                         } else {
1342                                 $like_op  = 'LIKE';
1343                                 $andor_op = 'OR';
1344                         }
1345
1346                         if ( $n && ! $exclude ) {
1347                                 $like = '%' . $wpdb->esc_like( $term ) . '%';
1348                                 $q['search_orderby_title'][] = $wpdb->prepare( "{$wpdb->posts}.post_title LIKE %s", $like );
1349                         }
1350
1351                         $like = $n . $wpdb->esc_like( $term ) . $n;
1352                         $search .= $wpdb->prepare( "{$searchand}(({$wpdb->posts}.post_title $like_op %s) $andor_op ({$wpdb->posts}.post_excerpt $like_op %s) $andor_op ({$wpdb->posts}.post_content $like_op %s))", $like, $like, $like );
1353                         $searchand = ' AND ';
1354                 }
1355
1356                 if ( ! empty( $search ) ) {
1357                         $search = " AND ({$search}) ";
1358                         if ( ! is_user_logged_in() ) {
1359                                 $search .= " AND ({$wpdb->posts}.post_password = '') ";
1360                         }
1361                 }
1362
1363                 return $search;
1364         }
1365
1366         /**
1367          * Check if the terms are suitable for searching.
1368          *
1369          * Uses an array of stopwords (terms) that are excluded from the separate
1370          * term matching when searching for posts. The list of English stopwords is
1371          * the approximate search engines list, and is translatable.
1372          *
1373          * @since 3.7.0
1374          *
1375          * @param array $terms Terms to check.
1376          * @return array Terms that are not stopwords.
1377          */
1378         protected function parse_search_terms( $terms ) {
1379                 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
1380                 $checked = array();
1381
1382                 $stopwords = $this->get_search_stopwords();
1383
1384                 foreach ( $terms as $term ) {
1385                         // keep before/after spaces when term is for exact match
1386                         if ( preg_match( '/^".+"$/', $term ) )
1387                                 $term = trim( $term, "\"'" );
1388                         else
1389                                 $term = trim( $term, "\"' " );
1390
1391                         // Avoid single A-Z and single dashes.
1392                         if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z\-]$/i', $term ) ) )
1393                                 continue;
1394
1395                         if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
1396                                 continue;
1397
1398                         $checked[] = $term;
1399                 }
1400
1401                 return $checked;
1402         }
1403
1404         /**
1405          * Retrieve stopwords used when parsing search terms.
1406          *
1407          * @since 3.7.0
1408          *
1409          * @return array Stopwords.
1410          */
1411         protected function get_search_stopwords() {
1412                 if ( isset( $this->stopwords ) )
1413                         return $this->stopwords;
1414
1415                 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
1416                  * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
1417                  * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
1418                  */
1419                 $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',
1420                         'Comma-separated list of search stopwords in your language' ) );
1421
1422                 $stopwords = array();
1423                 foreach ( $words as $word ) {
1424                         $word = trim( $word, "\r\n\t " );
1425                         if ( $word )
1426                                 $stopwords[] = $word;
1427                 }
1428
1429                 /**
1430                  * Filters stopwords used when parsing search terms.
1431                  *
1432                  * @since 3.7.0
1433                  *
1434                  * @param array $stopwords Stopwords.
1435                  */
1436                 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
1437                 return $this->stopwords;
1438         }
1439
1440         /**
1441          * Generate SQL for the ORDER BY condition based on passed search terms.
1442          *
1443          * @param array $q Query variables.
1444          * @return string ORDER BY clause.
1445          */
1446         protected function parse_search_order( &$q ) {
1447                 global $wpdb;
1448
1449                 if ( $q['search_terms_count'] > 1 ) {
1450                         $num_terms = count( $q['search_orderby_title'] );
1451
1452                         // If the search terms contain negative queries, don't bother ordering by sentence matches.
1453                         $like = '';
1454                         if ( ! preg_match( '/(?:\s|^)\-/', $q['s'] ) ) {
1455                                 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
1456                         }
1457
1458                         $search_orderby = '';
1459
1460                         // sentence match in 'post_title'
1461                         if ( $like ) {
1462                                 $search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_title LIKE %s THEN 1 ", $like );
1463                         }
1464
1465                         // sanity limit, sort as sentence when more than 6 terms
1466                         // (few searches are longer than 6 terms and most titles are not)
1467                         if ( $num_terms < 7 ) {
1468                                 // all words in title
1469                                 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
1470                                 // any word in title, not needed when $num_terms == 1
1471                                 if ( $num_terms > 1 )
1472                                         $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
1473                         }
1474
1475                         // Sentence match in 'post_content' and 'post_excerpt'.
1476                         if ( $like ) {
1477                                 $search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_excerpt LIKE %s THEN 4 ", $like );
1478                                 $search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_content LIKE %s THEN 5 ", $like );
1479                         }
1480
1481                         if ( $search_orderby ) {
1482                                 $search_orderby = '(CASE ' . $search_orderby . 'ELSE 6 END)';
1483                         }
1484                 } else {
1485                         // single word or sentence search
1486                         $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
1487                 }
1488
1489                 return $search_orderby;
1490         }
1491
1492         /**
1493          * If the passed orderby value is allowed, convert the alias to a
1494          * properly-prefixed orderby value.
1495          *
1496          * @since 4.0.0
1497          * @access protected
1498          *
1499          * @param string $orderby Alias for the field to order by.
1500          * @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
1501          */
1502         protected function parse_orderby( $orderby ) {
1503                 global $wpdb;
1504
1505                 // Used to filter values.
1506                 $allowed_keys = array(
1507                         'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
1508                         'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
1509                         'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
1510                 );
1511
1512                 $primary_meta_key = '';
1513                 $primary_meta_query = false;
1514                 $meta_clauses = $this->meta_query->get_clauses();
1515                 if ( ! empty( $meta_clauses ) ) {
1516                         $primary_meta_query = reset( $meta_clauses );
1517
1518                         if ( ! empty( $primary_meta_query['key'] ) ) {
1519                                 $primary_meta_key = $primary_meta_query['key'];
1520                                 $allowed_keys[] = $primary_meta_key;
1521                         }
1522
1523                         $allowed_keys[] = 'meta_value';
1524                         $allowed_keys[] = 'meta_value_num';
1525                         $allowed_keys   = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
1526                 }
1527
1528                 // If RAND() contains a seed value, sanitize and add to allowed keys.
1529                 $rand_with_seed = false;
1530                 if ( preg_match( '/RAND\(([0-9]+)\)/i', $orderby, $matches ) ) {
1531                         $orderby = sprintf( 'RAND(%s)', intval( $matches[1] ) );
1532                         $allowed_keys[] = $orderby;
1533                         $rand_with_seed = true;
1534                 }
1535
1536                 if ( ! in_array( $orderby, $allowed_keys, true ) ) {
1537                         return false;
1538                 }
1539
1540                 switch ( $orderby ) {
1541                         case 'post_name':
1542                         case 'post_author':
1543                         case 'post_date':
1544                         case 'post_title':
1545                         case 'post_modified':
1546                         case 'post_parent':
1547                         case 'post_type':
1548                         case 'ID':
1549                         case 'menu_order':
1550                         case 'comment_count':
1551                                 $orderby_clause = "{$wpdb->posts}.{$orderby}";
1552                                 break;
1553                         case 'rand':
1554                                 $orderby_clause = 'RAND()';
1555                                 break;
1556                         case $primary_meta_key:
1557                         case 'meta_value':
1558                                 if ( ! empty( $primary_meta_query['type'] ) ) {
1559                                         $orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
1560                                 } else {
1561                                         $orderby_clause = "{$primary_meta_query['alias']}.meta_value";
1562                                 }
1563                                 break;
1564                         case 'meta_value_num':
1565                                 $orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
1566                                 break;
1567                         default:
1568                                 if ( array_key_exists( $orderby, $meta_clauses ) ) {
1569                                         // $orderby corresponds to a meta_query clause.
1570                                         $meta_clause = $meta_clauses[ $orderby ];
1571                                         $orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
1572                                 } elseif ( $rand_with_seed ) {
1573                                         $orderby_clause = $orderby;
1574                                 } else {
1575                                         // Default: order by post field.
1576                                         $orderby_clause = "{$wpdb->posts}.post_" . sanitize_key( $orderby );
1577                                 }
1578
1579                                 break;
1580                 }
1581
1582                 return $orderby_clause;
1583         }
1584
1585         /**
1586          * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1587          *
1588          * @since 4.0.0
1589          * @access protected
1590          *
1591          * @param string $order The 'order' query variable.
1592          * @return string The sanitized 'order' query variable.
1593          */
1594         protected function parse_order( $order ) {
1595                 if ( ! is_string( $order ) || empty( $order ) ) {
1596                         return 'DESC';
1597                 }
1598
1599                 if ( 'ASC' === strtoupper( $order ) ) {
1600                         return 'ASC';
1601                 } else {
1602                         return 'DESC';
1603                 }
1604         }
1605
1606         /**
1607          * Sets the 404 property and saves whether query is feed.
1608          *
1609          * @since 2.0.0
1610          * @access public
1611          */
1612         public function set_404() {
1613                 $is_feed = $this->is_feed;
1614
1615                 $this->init_query_flags();
1616                 $this->is_404 = true;
1617
1618                 $this->is_feed = $is_feed;
1619         }
1620
1621         /**
1622          * Retrieve query variable.
1623          *
1624          * @since 1.5.0
1625          * @since 3.9.0 The `$default` argument was introduced.
1626          *
1627          * @access public
1628          *
1629          * @param string $query_var Query variable key.
1630          * @param mixed  $default   Optional. Value to return if the query variable is not set. Default empty.
1631          * @return mixed Contents of the query variable.
1632          */
1633         public function get( $query_var, $default = '' ) {
1634                 if ( isset( $this->query_vars[ $query_var ] ) ) {
1635                         return $this->query_vars[ $query_var ];
1636                 }
1637
1638                 return $default;
1639         }
1640
1641         /**
1642          * Set query variable.
1643          *
1644          * @since 1.5.0
1645          * @access public
1646          *
1647          * @param string $query_var Query variable key.
1648          * @param mixed  $value     Query variable value.
1649          */
1650         public function set($query_var, $value) {
1651                 $this->query_vars[$query_var] = $value;
1652         }
1653
1654         /**
1655          * Retrieve the posts based on query variables.
1656          *
1657          * There are a few filters and actions that can be used to modify the post
1658          * database query.
1659          *
1660          * @since 1.5.0
1661          * @access public
1662          *
1663          * @return array List of posts.
1664          */
1665         public function get_posts() {
1666                 global $wpdb;
1667
1668                 $this->parse_query();
1669
1670                 /**
1671                  * Fires after the query variable object is created, but before the actual query is run.
1672                  *
1673                  * Note: If using conditional tags, use the method versions within the passed instance
1674                  * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
1675                  * like is_main_query() test against the global $wp_query instance, not the passed one.
1676                  *
1677                  * @since 2.0.0
1678                  *
1679                  * @param WP_Query &$this The WP_Query instance (passed by reference).
1680                  */
1681                 do_action_ref_array( 'pre_get_posts', array( &$this ) );
1682
1683                 // Shorthand.
1684                 $q = &$this->query_vars;
1685
1686                 // Fill again in case pre_get_posts unset some vars.
1687                 $q = $this->fill_query_vars($q);
1688
1689                 // Parse meta query
1690                 $this->meta_query = new WP_Meta_Query();
1691                 $this->meta_query->parse_query_vars( $q );
1692
1693                 // Set a flag if a pre_get_posts hook changed the query vars.
1694                 $hash = md5( serialize( $this->query_vars ) );
1695                 if ( $hash != $this->query_vars_hash ) {
1696                         $this->query_vars_changed = true;
1697                         $this->query_vars_hash = $hash;
1698                 }
1699                 unset($hash);
1700
1701                 // First let's clear some variables
1702                 $distinct = '';
1703                 $whichauthor = '';
1704                 $whichmimetype = '';
1705                 $where = '';
1706                 $limits = '';
1707                 $join = '';
1708                 $search = '';
1709                 $groupby = '';
1710                 $post_status_join = false;
1711                 $page = 1;
1712
1713                 if ( isset( $q['caller_get_posts'] ) ) {
1714                         _deprecated_argument( 'WP_Query', '3.1.0', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
1715                         if ( !isset( $q['ignore_sticky_posts'] ) )
1716                                 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
1717                 }
1718
1719                 if ( !isset( $q['ignore_sticky_posts'] ) )
1720                         $q['ignore_sticky_posts'] = false;
1721
1722                 if ( !isset($q['suppress_filters']) )
1723                         $q['suppress_filters'] = false;
1724
1725                 if ( !isset($q['cache_results']) ) {
1726                         if ( wp_using_ext_object_cache() )
1727                                 $q['cache_results'] = false;
1728                         else
1729                                 $q['cache_results'] = true;
1730                 }
1731
1732                 if ( !isset($q['update_post_term_cache']) )
1733                         $q['update_post_term_cache'] = true;
1734
1735                 if ( ! isset( $q['lazy_load_term_meta'] ) ) {
1736                         $q['lazy_load_term_meta'] = $q['update_post_term_cache'];
1737                 }
1738
1739                 if ( !isset($q['update_post_meta_cache']) )
1740                         $q['update_post_meta_cache'] = true;
1741
1742                 if ( !isset($q['post_type']) ) {
1743                         if ( $this->is_search )
1744                                 $q['post_type'] = 'any';
1745                         else
1746                                 $q['post_type'] = '';
1747                 }
1748                 $post_type = $q['post_type'];
1749                 if ( empty( $q['posts_per_page'] ) ) {
1750                         $q['posts_per_page'] = get_option( 'posts_per_page' );
1751                 }
1752                 if ( isset($q['showposts']) && $q['showposts'] ) {
1753                         $q['showposts'] = (int) $q['showposts'];
1754                         $q['posts_per_page'] = $q['showposts'];
1755                 }
1756                 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
1757                         $q['posts_per_page'] = $q['posts_per_archive_page'];
1758                 if ( !isset($q['nopaging']) ) {
1759                         if ( $q['posts_per_page'] == -1 ) {
1760                                 $q['nopaging'] = true;
1761                         } else {
1762                                 $q['nopaging'] = false;
1763                         }
1764                 }
1765
1766                 if ( $this->is_feed ) {
1767                         // This overrides posts_per_page.
1768                         if ( ! empty( $q['posts_per_rss'] ) ) {
1769                                 $q['posts_per_page'] = $q['posts_per_rss'];
1770                         } else {
1771                                 $q['posts_per_page'] = get_option( 'posts_per_rss' );
1772                         }
1773                         $q['nopaging'] = false;
1774                 }
1775                 $q['posts_per_page'] = (int) $q['posts_per_page'];
1776                 if ( $q['posts_per_page'] < -1 )
1777                         $q['posts_per_page'] = abs($q['posts_per_page']);
1778                 elseif ( $q['posts_per_page'] == 0 )
1779                         $q['posts_per_page'] = 1;
1780
1781                 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
1782                         $q['comments_per_page'] = get_option('comments_per_page');
1783
1784                 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
1785                         $this->is_page = true;
1786                         $this->is_home = false;
1787                         $q['page_id'] = get_option('page_on_front');
1788                 }
1789
1790                 if ( isset($q['page']) ) {
1791                         $q['page'] = trim($q['page'], '/');
1792                         $q['page'] = absint($q['page']);
1793                 }
1794
1795                 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
1796                 if ( isset($q['no_found_rows']) )
1797                         $q['no_found_rows'] = (bool) $q['no_found_rows'];
1798                 else
1799                         $q['no_found_rows'] = false;
1800
1801                 switch ( $q['fields'] ) {
1802                         case 'ids':
1803                                 $fields = "{$wpdb->posts}.ID";
1804                                 break;
1805                         case 'id=>parent':
1806                                 $fields = "{$wpdb->posts}.ID, {$wpdb->posts}.post_parent";
1807                                 break;
1808                         default:
1809                                 $fields = "{$wpdb->posts}.*";
1810                 }
1811
1812                 if ( '' !== $q['menu_order'] ) {
1813                         $where .= " AND {$wpdb->posts}.menu_order = " . $q['menu_order'];
1814                 }
1815                 // The "m" parameter is meant for months but accepts datetimes of varying specificity
1816                 if ( $q['m'] ) {
1817                         $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
1818                         if ( strlen($q['m']) > 5 ) {
1819                                 $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
1820                         }
1821                         if ( strlen($q['m']) > 7 ) {
1822                                 $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
1823                         }
1824                         if ( strlen($q['m']) > 9 ) {
1825                                 $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
1826                         }
1827                         if ( strlen($q['m']) > 11 ) {
1828                                 $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
1829                         }
1830                         if ( strlen($q['m']) > 13 ) {
1831                                 $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
1832                         }
1833                 }
1834
1835                 // Handle the other individual date parameters
1836                 $date_parameters = array();
1837
1838                 if ( '' !== $q['hour'] )
1839                         $date_parameters['hour'] = $q['hour'];
1840
1841                 if ( '' !== $q['minute'] )
1842                         $date_parameters['minute'] = $q['minute'];
1843
1844                 if ( '' !== $q['second'] )
1845                         $date_parameters['second'] = $q['second'];
1846
1847                 if ( $q['year'] )
1848                         $date_parameters['year'] = $q['year'];
1849
1850                 if ( $q['monthnum'] )
1851                         $date_parameters['monthnum'] = $q['monthnum'];
1852
1853                 if ( $q['w'] )
1854                         $date_parameters['week'] = $q['w'];
1855
1856                 if ( $q['day'] )
1857                         $date_parameters['day'] = $q['day'];
1858
1859                 if ( $date_parameters ) {
1860                         $date_query = new WP_Date_Query( array( $date_parameters ) );
1861                         $where .= $date_query->get_sql();
1862                 }
1863                 unset( $date_parameters, $date_query );
1864
1865                 // Handle complex date queries
1866                 if ( ! empty( $q['date_query'] ) ) {
1867                         $this->date_query = new WP_Date_Query( $q['date_query'] );
1868                         $where .= $this->date_query->get_sql();
1869                 }
1870
1871
1872                 // If we've got a post_type AND it's not "any" post_type.
1873                 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
1874                         foreach ( (array)$q['post_type'] as $_post_type ) {
1875                                 $ptype_obj = get_post_type_object($_post_type);
1876                                 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
1877                                         continue;
1878
1879                                 if ( ! $ptype_obj->hierarchical ) {
1880                                         // Non-hierarchical post types can directly use 'name'.
1881                                         $q['name'] = $q[ $ptype_obj->query_var ];
1882                                 } else {
1883                                         // Hierarchical post types will operate through 'pagename'.
1884                                         $q['pagename'] = $q[ $ptype_obj->query_var ];
1885                                         $q['name'] = '';
1886                                 }
1887
1888                                 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
1889                                 break;
1890                         } //end foreach
1891                         unset($ptype_obj);
1892                 }
1893
1894                 if ( '' !== $q['title'] ) {
1895                         $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_title = %s", stripslashes( $q['title'] ) );
1896                 }
1897
1898                 // Parameters related to 'post_name'.
1899                 if ( '' != $q['name'] ) {
1900                         $q['name'] = sanitize_title_for_query( $q['name'] );
1901                         $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'";
1902                 } elseif ( '' != $q['pagename'] ) {
1903                         if ( isset($this->queried_object_id) ) {
1904                                 $reqpage = $this->queried_object_id;
1905                         } else {
1906                                 if ( 'page' != $q['post_type'] ) {
1907                                         foreach ( (array)$q['post_type'] as $_post_type ) {
1908                                                 $ptype_obj = get_post_type_object($_post_type);
1909                                                 if ( !$ptype_obj || !$ptype_obj->hierarchical )
1910                                                         continue;
1911
1912                                                 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
1913                                                 if ( $reqpage )
1914                                                         break;
1915                                         }
1916                                         unset($ptype_obj);
1917                                 } else {
1918                                         $reqpage = get_page_by_path($q['pagename']);
1919                                 }
1920                                 if ( !empty($reqpage) )
1921                                         $reqpage = $reqpage->ID;
1922                                 else
1923                                         $reqpage = 0;
1924                         }
1925
1926                         $page_for_posts = get_option('page_for_posts');
1927                         if  ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
1928                                 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
1929                                 $q['name'] = $q['pagename'];
1930                                 $where .= " AND ({$wpdb->posts}.ID = '$reqpage')";
1931                                 $reqpage_obj = get_post( $reqpage );
1932                                 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
1933                                         $this->is_attachment = true;
1934                                         $post_type = $q['post_type'] = 'attachment';
1935                                         $this->is_page = true;
1936                                         $q['attachment_id'] = $reqpage;
1937                                 }
1938                         }
1939                 } elseif ( '' != $q['attachment'] ) {
1940                         $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
1941                         $q['name'] = $q['attachment'];
1942                         $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
1943                 } elseif ( is_array( $q['post_name__in'] ) && ! empty( $q['post_name__in'] ) ) {
1944                         $q['post_name__in'] = array_map( 'sanitize_title_for_query', $q['post_name__in'] );
1945                         $post_name__in = "'" . implode( "','", $q['post_name__in'] ) . "'";
1946                         $where .= " AND {$wpdb->posts}.post_name IN ($post_name__in)";
1947                 }
1948
1949                 // If an attachment is requested by number, let it supersede any post number.
1950                 if ( $q['attachment_id'] )
1951                         $q['p'] = absint($q['attachment_id']);
1952
1953                 // If a post number is specified, load that post
1954                 if ( $q['p'] ) {
1955                         $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
1956                 } elseif ( $q['post__in'] ) {
1957                         $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
1958                         $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
1959                 } elseif ( $q['post__not_in'] ) {
1960                         $post__not_in = implode(',',  array_map( 'absint', $q['post__not_in'] ));
1961                         $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
1962                 }
1963
1964                 if ( is_numeric( $q['post_parent'] ) ) {
1965                         $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_parent = %d ", $q['post_parent'] );
1966                 } elseif ( $q['post_parent__in'] ) {
1967                         $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
1968                         $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
1969                 } elseif ( $q['post_parent__not_in'] ) {
1970                         $post_parent__not_in = implode( ',',  array_map( 'absint', $q['post_parent__not_in'] ) );
1971                         $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
1972                 }
1973
1974                 if ( $q['page_id'] ) {
1975                         if  ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
1976                                 $q['p'] = $q['page_id'];
1977                                 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
1978                         }
1979                 }
1980
1981                 // If a search pattern is specified, load the posts that match.
1982                 if ( strlen( $q['s'] ) ) {
1983                         $search = $this->parse_search( $q );
1984                 }
1985
1986                 if ( ! $q['suppress_filters'] ) {
1987                         /**
1988                          * Filters the search SQL that is used in the WHERE clause of WP_Query.
1989                          *
1990                          * @since 3.0.0
1991                          *
1992                          * @param string   $search Search SQL for WHERE clause.
1993                          * @param WP_Query $this   The current WP_Query object.
1994                          */
1995                         $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
1996                 }
1997
1998                 // Taxonomies
1999                 if ( !$this->is_singular ) {
2000                         $this->parse_tax_query( $q );
2001
2002                         $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2003
2004                         $join .= $clauses['join'];
2005                         $where .= $clauses['where'];
2006                 }
2007
2008                 if ( $this->is_tax ) {
2009                         if ( empty($post_type) ) {
2010                                 // Do a fully inclusive search for currently registered post types of queried taxonomies
2011                                 $post_type = array();
2012                                 $taxonomies = array_keys( $this->tax_query->queried_terms );
2013                                 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2014                                         $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2015                                         if ( array_intersect( $taxonomies, $object_taxonomies ) )
2016                                                 $post_type[] = $pt;
2017                                 }
2018                                 if ( ! $post_type )
2019                                         $post_type = 'any';
2020                                 elseif ( count( $post_type ) == 1 )
2021                                         $post_type = $post_type[0];
2022
2023                                 $post_status_join = true;
2024                         } elseif ( in_array('attachment', (array) $post_type) ) {
2025                                 $post_status_join = true;
2026                         }
2027                 }
2028
2029                 /*
2030                  * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2031                  * 'category_name' vars are set for backward compatibility.
2032                  */
2033                 if ( ! empty( $this->tax_query->queried_terms ) ) {
2034
2035                         /*
2036                          * Set 'taxonomy', 'term', and 'term_id' to the
2037                          * first taxonomy other than 'post_tag' or 'category'.
2038                          */
2039                         if ( ! isset( $q['taxonomy'] ) ) {
2040                                 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2041                                         if ( empty( $queried_items['terms'][0] ) ) {
2042                                                 continue;
2043                                         }
2044
2045                                         if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2046                                                 $q['taxonomy'] = $queried_taxonomy;
2047
2048                                                 if ( 'slug' === $queried_items['field'] ) {
2049                                                         $q['term'] = $queried_items['terms'][0];
2050                                                 } else {
2051                                                         $q['term_id'] = $queried_items['terms'][0];
2052                                                 }
2053
2054                                                 // Take the first one we find.
2055                                                 break;
2056                                         }
2057                                 }
2058                         }
2059
2060                         // 'cat', 'category_name', 'tag_id'
2061                         foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2062                                 if ( empty( $queried_items['terms'][0] ) ) {
2063                                         continue;
2064                                 }
2065
2066                                 if ( 'category' === $queried_taxonomy ) {
2067                                         $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2068                                         if ( $the_cat ) {
2069                                                 $this->set( 'cat', $the_cat->term_id );
2070                                                 $this->set( 'category_name', $the_cat->slug );
2071                                         }
2072                                         unset( $the_cat );
2073                                 }
2074
2075                                 if ( 'post_tag' === $queried_taxonomy ) {
2076                                         $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2077                                         if ( $the_tag ) {
2078                                                 $this->set( 'tag_id', $the_tag->term_id );
2079                                         }
2080                                         unset( $the_tag );
2081                                 }
2082                         }
2083                 }
2084
2085                 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2086                         $groupby = "{$wpdb->posts}.ID";
2087                 }
2088
2089                 // Author/user stuff
2090
2091                 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2092                         $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2093                         $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2094                         foreach ( $authors as $author ) {
2095                                 $key = $author > 0 ? 'author__in' : 'author__not_in';
2096                                 $q[$key][] = abs( $author );
2097                         }
2098                         $q['author'] = implode( ',', $authors );
2099                 }
2100
2101                 if ( ! empty( $q['author__not_in'] ) ) {
2102                         $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2103                         $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2104                 } elseif ( ! empty( $q['author__in'] ) ) {
2105                         $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2106                         $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2107                 }
2108
2109                 // Author stuff for nice URLs
2110
2111                 if ( '' != $q['author_name'] ) {
2112                         if ( strpos($q['author_name'], '/') !== false ) {
2113                                 $q['author_name'] = explode('/', $q['author_name']);
2114                                 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2115                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2116                                 } else {
2117                                         $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2118                                 }
2119                         }
2120                         $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2121                         $q['author'] = get_user_by('slug', $q['author_name']);
2122                         if ( $q['author'] )
2123                                 $q['author'] = $q['author']->ID;
2124                         $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')';
2125                 }
2126
2127                 // MIME-Type stuff for attachment browsing
2128
2129                 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] ) {
2130                         $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2131                 }
2132                 $where .= $search . $whichauthor . $whichmimetype;
2133
2134                 if ( ! empty( $this->meta_query->queries ) ) {
2135                         $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
2136                         $join   .= $clauses['join'];
2137                         $where  .= $clauses['where'];
2138                 }
2139
2140                 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2141                 if ( ! isset( $q['order'] ) ) {
2142                         $q['order'] = $rand ? '' : 'DESC';
2143                 } else {
2144                         $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2145                 }
2146
2147                 // Order by.
2148                 if ( empty( $q['orderby'] ) ) {
2149                         /*
2150                          * Boolean false or empty array blanks out ORDER BY,
2151                          * while leaving the value unset or otherwise empty sets the default.
2152                          */
2153                         if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2154                                 $orderby = '';
2155                         } else {
2156                                 $orderby = "{$wpdb->posts}.post_date " . $q['order'];
2157                         }
2158                 } elseif ( 'none' == $q['orderby'] ) {
2159                         $orderby = '';
2160                 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2161                         $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2162                 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2163                         $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2164                 } elseif ( $q['orderby'] == 'post_name__in' && ! empty( $post_name__in ) ) {
2165                         $orderby = "FIELD( {$wpdb->posts}.post_name, $post_name__in )";
2166                 } else {
2167                         $orderby_array = array();
2168                         if ( is_array( $q['orderby'] ) ) {
2169                                 foreach ( $q['orderby'] as $_orderby => $order ) {
2170                                         $orderby = addslashes_gpc( urldecode( $_orderby ) );
2171                                         $parsed  = $this->parse_orderby( $orderby );
2172
2173                                         if ( ! $parsed ) {
2174                                                 continue;
2175                                         }
2176
2177                                         $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2178                                 }
2179                                 $orderby = implode( ', ', $orderby_array );
2180
2181                         } else {
2182                                 $q['orderby'] = urldecode( $q['orderby'] );
2183                                 $q['orderby'] = addslashes_gpc( $q['orderby'] );
2184
2185                                 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
2186                                         $parsed = $this->parse_orderby( $orderby );
2187                                         // Only allow certain values for safety.
2188                                         if ( ! $parsed ) {
2189                                                 continue;
2190                                         }
2191
2192                                         $orderby_array[] = $parsed;
2193                                 }
2194                                 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
2195
2196                                 if ( empty( $orderby ) ) {
2197                                         $orderby = "{$wpdb->posts}.post_date " . $q['order'];
2198                                 } elseif ( ! empty( $q['order'] ) ) {
2199                                         $orderby .= " {$q['order']}";
2200                                 }
2201                         }
2202                 }
2203
2204                 // Order search results by relevance only when another "orderby" is not specified in the query.
2205                 if ( ! empty( $q['s'] ) ) {
2206                         $search_orderby = '';
2207                         if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
2208                                 $search_orderby = $this->parse_search_order( $q );
2209
2210                         if ( ! $q['suppress_filters'] ) {
2211                                 /**
2212                                  * Filters the ORDER BY used when ordering search results.
2213                                  *
2214                                  * @since 3.7.0
2215                                  *
2216                                  * @param string   $search_orderby The ORDER BY clause.
2217                                  * @param WP_Query $this           The current WP_Query instance.
2218                                  */
2219                                 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
2220                         }
2221
2222                         if ( $search_orderby )
2223                                 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
2224                 }
2225
2226                 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
2227                         $post_type_cap = 'multiple_post_type';
2228                 } else {
2229                         if ( is_array( $post_type ) )
2230                                 $post_type = reset( $post_type );
2231                         $post_type_object = get_post_type_object( $post_type );
2232                         if ( empty( $post_type_object ) )
2233                                 $post_type_cap = $post_type;
2234                 }
2235
2236                 if ( isset( $q['post_password'] ) ) {
2237                         $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_password = %s", $q['post_password'] );
2238                         if ( empty( $q['perm'] ) ) {
2239                                 $q['perm'] = 'readable';
2240                         }
2241                 } elseif ( isset( $q['has_password'] ) ) {
2242                         $where .= sprintf( " AND {$wpdb->posts}.post_password %s ''", $q['has_password'] ? '!=' : '=' );
2243                 }
2244
2245                 if ( ! empty( $q['comment_status'] ) ) {
2246                         $where .= $wpdb->prepare( " AND {$wpdb->posts}.comment_status = %s ", $q['comment_status'] );
2247                 }
2248
2249                 if ( ! empty( $q['ping_status'] ) )  {
2250                         $where .= $wpdb->prepare( " AND {$wpdb->posts}.ping_status = %s ", $q['ping_status'] );
2251                 }
2252
2253                 if ( 'any' == $post_type ) {
2254                         $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
2255                         if ( empty( $in_search_post_types ) ) {
2256                                 $where .= ' AND 1=0 ';
2257                         } else {
2258                                 $where .= " AND {$wpdb->posts}.post_type IN ('" . join( "', '", array_map( 'esc_sql', $in_search_post_types ) ) . "')";
2259                         }
2260                 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
2261                         $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", esc_sql( $post_type ) ) . "')";
2262                 } elseif ( ! empty( $post_type ) ) {
2263                         $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_type = %s", $post_type );
2264                         $post_type_object = get_post_type_object ( $post_type );
2265                 } elseif ( $this->is_attachment ) {
2266                         $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
2267                         $post_type_object = get_post_type_object ( 'attachment' );
2268                 } elseif ( $this->is_page ) {
2269                         $where .= " AND {$wpdb->posts}.post_type = 'page'";
2270                         $post_type_object = get_post_type_object ( 'page' );
2271                 } else {
2272                         $where .= " AND {$wpdb->posts}.post_type = 'post'";
2273                         $post_type_object = get_post_type_object ( 'post' );
2274                 }
2275
2276                 $edit_cap = 'edit_post';
2277                 $read_cap = 'read_post';
2278
2279                 if ( ! empty( $post_type_object ) ) {
2280                         $edit_others_cap = $post_type_object->cap->edit_others_posts;
2281                         $read_private_cap = $post_type_object->cap->read_private_posts;
2282                 } else {
2283                         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
2284                         $read_private_cap = 'read_private_' . $post_type_cap . 's';
2285                 }
2286
2287                 $user_id = get_current_user_id();
2288
2289                 $q_status = array();
2290                 if ( ! empty( $q['post_status'] ) ) {
2291                         $statuswheres = array();
2292                         $q_status = $q['post_status'];
2293                         if ( ! is_array( $q_status ) )
2294                                 $q_status = explode(',', $q_status);
2295                         $r_status = array();
2296                         $p_status = array();
2297                         $e_status = array();
2298                         if ( in_array( 'any', $q_status ) ) {
2299                                 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
2300                                         if ( ! in_array( $status, $q_status ) ) {
2301                                                 $e_status[] = "{$wpdb->posts}.post_status <> '$status'";
2302                                         }
2303                                 }
2304                         } else {
2305                                 foreach ( get_post_stati() as $status ) {
2306                                         if ( in_array( $status, $q_status ) ) {
2307                                                 if ( 'private' == $status ) {
2308                                                         $p_status[] = "{$wpdb->posts}.post_status = '$status'";
2309                                                 } else {
2310                                                         $r_status[] = "{$wpdb->posts}.post_status = '$status'";
2311                                                 }
2312                                         }
2313                                 }
2314                         }
2315
2316                         if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
2317                                 $r_status = array_merge($r_status, $p_status);
2318                                 unset($p_status);
2319                         }
2320
2321                         if ( !empty($e_status) ) {
2322                                 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
2323                         }
2324                         if ( !empty($r_status) ) {
2325                                 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) ) {
2326                                         $statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
2327                                 } else {
2328                                         $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
2329                                 }
2330                         }
2331                         if ( !empty($p_status) ) {
2332                                 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) ) {
2333                                         $statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
2334                                 } else {
2335                                         $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
2336                                 }
2337                         }
2338                         if ( $post_status_join ) {
2339                                 $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) ";
2340                                 foreach ( $statuswheres as $index => $statuswhere ) {
2341                                         $statuswheres[$index] = "($statuswhere OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace( $wpdb->posts, 'p2', $statuswhere ) . "))";
2342                                 }
2343                         }
2344                         $where_status = implode( ' OR ', $statuswheres );
2345                         if ( ! empty( $where_status ) ) {
2346                                 $where .= " AND ($where_status)";
2347                         }
2348                 } elseif ( !$this->is_singular ) {
2349                         $where .= " AND ({$wpdb->posts}.post_status = 'publish'";
2350
2351                         // Add public states.
2352                         $public_states = get_post_stati( array('public' => true) );
2353                         foreach ( (array) $public_states as $state ) {
2354                                 if ( 'publish' == $state ) // Publish is hard-coded above.
2355                                         continue;
2356                                 $where .= " OR {$wpdb->posts}.post_status = '$state'";
2357                         }
2358
2359                         if ( $this->is_admin ) {
2360                                 // Add protected states that should show in the admin all list.
2361                                 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
2362                                 foreach ( (array) $admin_all_states as $state ) {
2363                                         $where .= " OR {$wpdb->posts}.post_status = '$state'";
2364                                 }
2365                         }
2366
2367                         if ( is_user_logged_in() ) {
2368                                 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
2369                                 $private_states = get_post_stati( array('private' => true) );
2370                                 foreach ( (array) $private_states as $state ) {
2371                                         $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'";
2372                                 }
2373                         }
2374
2375                         $where .= ')';
2376                 }
2377
2378                 /*
2379                  * Apply filters on where and join prior to paging so that any
2380                  * manipulations to them are reflected in the paging by day queries.
2381                  */
2382                 if ( !$q['suppress_filters'] ) {
2383                         /**
2384                          * Filters the WHERE clause of the query.
2385                          *
2386                          * @since 1.5.0
2387                          *
2388                          * @param string   $where The WHERE clause of the query.
2389                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2390                          */
2391                         $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
2392
2393                         /**
2394                          * Filters the JOIN clause of the query.
2395                          *
2396                          * @since 1.5.0
2397                          *
2398                          * @param string   $where The JOIN clause of the query.
2399                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2400                          */
2401                         $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
2402                 }
2403
2404                 // Paging
2405                 if ( empty($q['nopaging']) && !$this->is_singular ) {
2406                         $page = absint($q['paged']);
2407                         if ( !$page )
2408                                 $page = 1;
2409
2410                         // If 'offset' is provided, it takes precedence over 'paged'.
2411                         if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
2412                                 $q['offset'] = absint( $q['offset'] );
2413                                 $pgstrt = $q['offset'] . ', ';
2414                         } else {
2415                                 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
2416                         }
2417                         $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
2418                 }
2419
2420                 // Comments feeds
2421                 if ( $this->is_comment_feed && ! $this->is_singular ) {
2422                         if ( $this->is_archive || $this->is_search ) {
2423                                 $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) $join ";
2424                                 $cwhere = "WHERE comment_approved = '1' $where";
2425                                 $cgroupby = "{$wpdb->comments}.comment_id";
2426                         } else { // Other non singular e.g. front
2427                                 $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )";
2428                                 $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' AND post_type = 'attachment' ) ) AND comment_approved = '1'";
2429                                 $cgroupby = '';
2430                         }
2431
2432                         if ( !$q['suppress_filters'] ) {
2433                                 /**
2434                                  * Filters the JOIN clause of the comments feed query before sending.
2435                                  *
2436                                  * @since 2.2.0
2437                                  *
2438                                  * @param string   $cjoin The JOIN clause of the query.
2439                                  * @param WP_Query &$this The WP_Query instance (passed by reference).
2440                                  */
2441                                 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
2442
2443                                 /**
2444                                  * Filters the WHERE clause of the comments feed query before sending.
2445                                  *
2446                                  * @since 2.2.0
2447                                  *
2448                                  * @param string   $cwhere The WHERE clause of the query.
2449                                  * @param WP_Query &$this  The WP_Query instance (passed by reference).
2450                                  */
2451                                 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
2452
2453                                 /**
2454                                  * Filters the GROUP BY clause of the comments feed query before sending.
2455                                  *
2456                                  * @since 2.2.0
2457                                  *
2458                                  * @param string   $cgroupby The GROUP BY clause of the query.
2459                                  * @param WP_Query &$this    The WP_Query instance (passed by reference).
2460                                  */
2461                                 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
2462
2463                                 /**
2464                                  * Filters the ORDER BY clause of the comments feed query before sending.
2465                                  *
2466                                  * @since 2.8.0
2467                                  *
2468                                  * @param string   $corderby The ORDER BY clause of the query.
2469                                  * @param WP_Query &$this    The WP_Query instance (passed by reference).
2470                                  */
2471                                 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
2472
2473                                 /**
2474                                  * Filters the LIMIT clause of the comments feed query before sending.
2475                                  *
2476                                  * @since 2.8.0
2477                                  *
2478                                  * @param string   $climits The JOIN clause of the query.
2479                                  * @param WP_Query &$this   The WP_Query instance (passed by reference).
2480                                  */
2481                                 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
2482                         }
2483                         $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
2484                         $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
2485
2486                         $comments = (array) $wpdb->get_results("SELECT $distinct {$wpdb->comments}.* FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits");
2487                         // Convert to WP_Comment
2488                         $this->comments = array_map( 'get_comment', $comments );
2489                         $this->comment_count = count($this->comments);
2490
2491                         $post_ids = array();
2492
2493                         foreach ( $this->comments as $comment )
2494                                 $post_ids[] = (int) $comment->comment_post_ID;
2495
2496                         $post_ids = join(',', $post_ids);
2497                         $join = '';
2498                         if ( $post_ids ) {
2499                                 $where = "AND {$wpdb->posts}.ID IN ($post_ids) ";
2500                         } else {
2501                                 $where = "AND 0";
2502                         }
2503                 }
2504
2505                 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
2506
2507                 /*
2508                  * Apply post-paging filters on where and join. Only plugins that
2509                  * manipulate paging queries should use these hooks.
2510                  */
2511                 if ( !$q['suppress_filters'] ) {
2512                         /**
2513                          * Filters the WHERE clause of the query.
2514                          *
2515                          * Specifically for manipulating paging queries.
2516                          *
2517                          * @since 1.5.0
2518                          *
2519                          * @param string   $where The WHERE clause of the query.
2520                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2521                          */
2522                         $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
2523
2524                         /**
2525                          * Filters the GROUP BY clause of the query.
2526                          *
2527                          * @since 2.0.0
2528                          *
2529                          * @param string   $groupby The GROUP BY clause of the query.
2530                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
2531                          */
2532                         $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
2533
2534                         /**
2535                          * Filters the JOIN clause of the query.
2536                          *
2537                          * Specifically for manipulating paging queries.
2538                          *
2539                          * @since 1.5.0
2540                          *
2541                          * @param string   $join  The JOIN clause of the query.
2542                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2543                          */
2544                         $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
2545
2546                         /**
2547                          * Filters the ORDER BY clause of the query.
2548                          *
2549                          * @since 1.5.1
2550                          *
2551                          * @param string   $orderby The ORDER BY clause of the query.
2552                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
2553                          */
2554                         $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
2555
2556                         /**
2557                          * Filters the DISTINCT clause of the query.
2558                          *
2559                          * @since 2.1.0
2560                          *
2561                          * @param string   $distinct The DISTINCT clause of the query.
2562                          * @param WP_Query &$this    The WP_Query instance (passed by reference).
2563                          */
2564                         $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
2565
2566                         /**
2567                          * Filters the LIMIT clause of the query.
2568                          *
2569                          * @since 2.1.0
2570                          *
2571                          * @param string   $limits The LIMIT clause of the query.
2572                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
2573                          */
2574                         $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
2575
2576                         /**
2577                          * Filters the SELECT clause of the query.
2578                          *
2579                          * @since 2.1.0
2580                          *
2581                          * @param string   $fields The SELECT clause of the query.
2582                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
2583                          */
2584                         $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
2585
2586                         /**
2587                          * Filters all query clauses at once, for convenience.
2588                          *
2589                          * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
2590                          * fields (SELECT), and LIMITS clauses.
2591                          *
2592                          * @since 3.1.0
2593                          *
2594                          * @param array    $clauses The list of clauses for the query.
2595                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
2596                          */
2597                         $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
2598
2599                         $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
2600                         $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
2601                         $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
2602                         $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
2603                         $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
2604                         $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
2605                         $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
2606                 }
2607
2608                 /**
2609                  * Fires to announce the query's current selection parameters.
2610                  *
2611                  * For use by caching plugins.
2612                  *
2613                  * @since 2.3.0
2614                  *
2615                  * @param string $selection The assembled selection query.
2616                  */
2617                 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
2618
2619                 /*
2620                  * Filters again for the benefit of caching plugins.
2621                  * Regular plugins should use the hooks above.
2622                  */
2623                 if ( !$q['suppress_filters'] ) {
2624                         /**
2625                          * Filters the WHERE clause of the query.
2626                          *
2627                          * For use by caching plugins.
2628                          *
2629                          * @since 2.5.0
2630                          *
2631                          * @param string   $where The WHERE clause of the query.
2632                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2633                          */
2634                         $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
2635
2636                         /**
2637                          * Filters the GROUP BY clause of the query.
2638                          *
2639                          * For use by caching plugins.
2640                          *
2641                          * @since 2.5.0
2642                          *
2643                          * @param string   $groupby The GROUP BY clause of the query.
2644                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
2645                          */
2646                         $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
2647
2648                         /**
2649                          * Filters the JOIN clause of the query.
2650                          *
2651                          * For use by caching plugins.
2652                          *
2653                          * @since 2.5.0
2654                          *
2655                          * @param string   $join  The JOIN clause of the query.
2656                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2657                          */
2658                         $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
2659
2660                         /**
2661                          * Filters the ORDER BY clause of the query.
2662                          *
2663                          * For use by caching plugins.
2664                          *
2665                          * @since 2.5.0
2666                          *
2667                          * @param string   $orderby The ORDER BY clause of the query.
2668                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
2669                          */
2670                         $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
2671
2672                         /**
2673                          * Filters the DISTINCT clause of the query.
2674                          *
2675                          * For use by caching plugins.
2676                          *
2677                          * @since 2.5.0
2678                          *
2679                          * @param string   $distinct The DISTINCT clause of the query.
2680                          * @param WP_Query &$this    The WP_Query instance (passed by reference).
2681                          */
2682                         $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
2683
2684                         /**
2685                          * Filters the SELECT clause of the query.
2686                          *
2687                          * For use by caching plugins.
2688                          *
2689                          * @since 2.5.0
2690                          *
2691                          * @param string   $fields The SELECT clause of the query.
2692                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
2693                          */
2694                         $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
2695
2696                         /**
2697                          * Filters the LIMIT clause of the query.
2698                          *
2699                          * For use by caching plugins.
2700                          *
2701                          * @since 2.5.0
2702                          *
2703                          * @param string   $limits The LIMIT clause of the query.
2704                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
2705                          */
2706                         $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
2707
2708                         /**
2709                          * Filters all query clauses at once, for convenience.
2710                          *
2711                          * For use by caching plugins.
2712                          *
2713                          * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
2714                          * fields (SELECT), and LIMITS clauses.
2715                          *
2716                          * @since 3.1.0
2717                          *
2718                          * @param array    $pieces The pieces of the query.
2719                          * @param WP_Query &$this  The WP_Query instance (passed by reference).
2720                          */
2721                         $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
2722
2723                         $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
2724                         $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
2725                         $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
2726                         $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
2727                         $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
2728                         $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
2729                         $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
2730                 }
2731
2732                 if ( ! empty($groupby) )
2733                         $groupby = 'GROUP BY ' . $groupby;
2734                 if ( !empty( $orderby ) )
2735                         $orderby = 'ORDER BY ' . $orderby;
2736
2737                 $found_rows = '';
2738                 if ( !$q['no_found_rows'] && !empty($limits) )
2739                         $found_rows = 'SQL_CALC_FOUND_ROWS';
2740
2741                 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM {$wpdb->posts} $join WHERE 1=1 $where $groupby $orderby $limits";
2742
2743                 if ( !$q['suppress_filters'] ) {
2744                         /**
2745                          * Filters the completed SQL query before sending.
2746                          *
2747                          * @since 2.0.0
2748                          *
2749                          * @param string   $request The complete SQL query.
2750                          * @param WP_Query &$this   The WP_Query instance (passed by reference).
2751                          */
2752                         $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
2753                 }
2754
2755                 /**
2756                  * Filters the posts array before the query takes place.
2757                  *
2758                  * Return a non-null value to bypass WordPress's default post queries.
2759                  *
2760                  * Filtering functions that require pagination information are encouraged to set
2761                  * the `found_posts` and `max_num_pages` properties of the WP_Query object,
2762                  * passed to the filter by reference. If WP_Query does not perform a database
2763                  * query, it will not have enough information to generate these values itself.
2764                  *
2765                  * @since 4.6.0
2766                  *
2767                  * @param array|null $posts Return an array of post data to short-circuit WP's query,
2768                  *                          or null to allow WP to run its normal queries.
2769                  * @param WP_Query   $this  The WP_Query instance, passed by reference.
2770                  */
2771                 $this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );
2772
2773                 if ( 'ids' == $q['fields'] ) {
2774                         if ( null === $this->posts ) {
2775                                 $this->posts = $wpdb->get_col( $this->request );
2776                         }
2777
2778                         $this->posts = array_map( 'intval', $this->posts );
2779                         $this->post_count = count( $this->posts );
2780                         $this->set_found_posts( $q, $limits );
2781
2782                         return $this->posts;
2783                 }
2784
2785                 if ( 'id=>parent' == $q['fields'] ) {
2786                         if ( null === $this->posts ) {
2787                                 $this->posts = $wpdb->get_results( $this->request );
2788                         }
2789
2790                         $this->post_count = count( $this->posts );
2791                         $this->set_found_posts( $q, $limits );
2792
2793                         $r = array();
2794                         foreach ( $this->posts as $key => $post ) {
2795                                 $this->posts[ $key ]->ID = (int) $post->ID;
2796                                 $this->posts[ $key ]->post_parent = (int) $post->post_parent;
2797
2798                                 $r[ (int) $post->ID ] = (int) $post->post_parent;
2799                         }
2800
2801                         return $r;
2802                 }
2803
2804                 if ( null === $this->posts ) {
2805                         $split_the_query = ( $old_request == $this->request && "{$wpdb->posts}.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
2806
2807                         /**
2808                          * Filters whether to split the query.
2809                          *
2810                          * Splitting the query will cause it to fetch just the IDs of the found posts
2811                          * (and then individually fetch each post by ID), rather than fetching every
2812                          * complete row at once. One massive result vs. many small results.
2813                          *
2814                          * @since 3.4.0
2815                          *
2816                          * @param bool     $split_the_query Whether or not to split the query.
2817                          * @param WP_Query $this            The WP_Query instance.
2818                          */
2819                         $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
2820
2821                         if ( $split_the_query ) {
2822                                 // First get the IDs and then fill in the objects
2823
2824                                 $this->request = "SELECT $found_rows $distinct {$wpdb->posts}.ID FROM {$wpdb->posts} $join WHERE 1=1 $where $groupby $orderby $limits";
2825
2826                                 /**
2827                                  * Filters the Post IDs SQL request before sending.
2828                                  *
2829                                  * @since 3.4.0
2830                                  *
2831                                  * @param string   $request The post ID request.
2832                                  * @param WP_Query $this    The WP_Query instance.
2833                                  */
2834                                 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
2835
2836                                 $ids = $wpdb->get_col( $this->request );
2837
2838                                 if ( $ids ) {
2839                                         $this->posts = $ids;
2840                                         $this->set_found_posts( $q, $limits );
2841                                         _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
2842                                 } else {
2843                                         $this->posts = array();
2844                                 }
2845                         } else {
2846                                 $this->posts = $wpdb->get_results( $this->request );
2847                                 $this->set_found_posts( $q, $limits );
2848                         }
2849                 }
2850
2851                 // Convert to WP_Post objects.
2852                 if ( $this->posts ) {
2853                         $this->posts = array_map( 'get_post', $this->posts );
2854                 }
2855
2856                 if ( ! $q['suppress_filters'] ) {
2857                         /**
2858                          * Filters the raw post results array, prior to status checks.
2859                          *
2860                          * @since 2.3.0
2861                          *
2862                          * @param array    $posts The post results array.
2863                          * @param WP_Query &$this The WP_Query instance (passed by reference).
2864                          */
2865                         $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
2866                 }
2867
2868                 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
2869                         /** This filter is documented in wp-includes/query.php */
2870                         $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
2871
2872                         /** This filter is documented in wp-includes/query.php */
2873                         $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
2874
2875                         /** This filter is documented in wp-includes/query.php */
2876                         $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
2877                         $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
2878
2879                         /** This filter is documented in wp-includes/query.php */
2880                         $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
2881                         $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
2882
2883                         /** This filter is documented in wp-includes/query.php */
2884                         $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
2885
2886                         $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits";
2887                         $comments = $wpdb->get_results($comments_request);
2888                         // Convert to WP_Comment
2889                         $this->comments = array_map( 'get_comment', $comments );
2890                         $this->comment_count = count($this->comments);
2891                 }
2892
2893                 // Check post status to determine if post should be displayed.
2894                 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
2895                         $status = get_post_status($this->posts[0]);
2896                         if ( 'attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent ) {
2897                                 $this->is_page = false;
2898                                 $this->is_single = true;
2899                                 $this->is_attachment = true;
2900                         }
2901                         $post_status_obj = get_post_status_object($status);
2902
2903                         // If the post_status was specifically requested, let it pass through.
2904                         if ( !$post_status_obj->public && ! in_array( $status, $q_status ) ) {
2905
2906                                 if ( ! is_user_logged_in() ) {
2907                                         // User must be logged in to view unpublished posts.
2908                                         $this->posts = array();
2909                                 } else {
2910                                         if  ( $post_status_obj->protected ) {
2911                                                 // User must have edit permissions on the draft to preview.
2912                                                 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
2913                                                         $this->posts = array();
2914                                                 } else {
2915                                                         $this->is_preview = true;
2916                                                         if ( 'future' != $status )
2917                                                                 $this->posts[0]->post_date = current_time('mysql');
2918                                                 }
2919                                         } elseif ( $post_status_obj->private ) {
2920                                                 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
2921                                                         $this->posts = array();
2922                                         } else {
2923                                                 $this->posts = array();
2924                                         }
2925                                 }
2926                         }
2927
2928                         if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
2929                                 /**
2930                                  * Filters the single post for preview mode.
2931                                  *
2932                                  * @since 2.7.0
2933                                  *
2934                                  * @param WP_Post  $post_preview  The Post object.
2935                                  * @param WP_Query &$this         The WP_Query instance (passed by reference).
2936                                  */
2937                                 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
2938                         }
2939                 }
2940
2941                 // Put sticky posts at the top of the posts array
2942                 $sticky_posts = get_option('sticky_posts');
2943                 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
2944                         $num_posts = count($this->posts);
2945                         $sticky_offset = 0;
2946                         // Loop over posts and relocate stickies to the front.
2947                         for ( $i = 0; $i < $num_posts; $i++ ) {
2948                                 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
2949                                         $sticky_post = $this->posts[$i];
2950                                         // Remove sticky from current position
2951                                         array_splice($this->posts, $i, 1);
2952                                         // Move to front, after other stickies
2953                                         array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
2954                                         // Increment the sticky offset. The next sticky will be placed at this offset.
2955                                         $sticky_offset++;
2956                                         // Remove post from sticky posts array
2957                                         $offset = array_search($sticky_post->ID, $sticky_posts);
2958                                         unset( $sticky_posts[$offset] );
2959                                 }
2960                         }
2961
2962                         // If any posts have been excluded specifically, Ignore those that are sticky.
2963                         if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
2964                                 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
2965
2966                         // Fetch sticky posts that weren't in the query results
2967                         if ( !empty($sticky_posts) ) {
2968                                 $stickies = get_posts( array(
2969                                         'post__in' => $sticky_posts,
2970                                         'post_type' => $post_type,
2971                                         'post_status' => 'publish',
2972                                         'nopaging' => true
2973                                 ) );
2974
2975                                 foreach ( $stickies as $sticky_post ) {
2976                                         array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
2977                                         $sticky_offset++;
2978                                 }
2979                         }
2980                 }
2981
2982                 // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
2983                 if ( ! empty( $this->comments ) ) {
2984                         wp_queue_comments_for_comment_meta_lazyload( $this->comments );
2985        &nb