5 * The query API attempts to get which part of WordPress the user is on. It
6 * also provides functionality for getting URL query information.
8 * @link https://codex.wordpress.org/The_Loop More information on The Loop.
15 * Retrieve variable in the WP_Query class.
18 * @since 3.9.0 The `$default` argument was introduced.
20 * @global WP_Query $wp_query Global WP_Query instance.
22 * @param string $var The variable key to retrieve.
23 * @param mixed $default Optional. Value to return if the query variable is not set. Default empty.
24 * @return mixed Contents of the query variable.
26 function get_query_var( $var, $default = '' ) {
28 return $wp_query->get( $var, $default );
32 * Retrieve the currently-queried object.
34 * Wrapper for WP_Query::get_queried_object().
39 * @global WP_Query $wp_query Global WP_Query instance.
41 * @return object Queried object.
43 function get_queried_object() {
45 return $wp_query->get_queried_object();
49 * Retrieve ID of the current queried object.
51 * Wrapper for WP_Query::get_queried_object_id().
55 * @global WP_Query $wp_query Global WP_Query instance.
57 * @return int ID of the queried object.
59 function get_queried_object_id() {
61 return $wp_query->get_queried_object_id();
69 * @global WP_Query $wp_query Global WP_Query instance.
71 * @param string $var Query variable key.
72 * @param mixed $value Query variable value.
74 function set_query_var( $var, $value ) {
76 $wp_query->set( $var, $value );
80 * Set up The Loop with query parameters.
82 * This will override the current WordPress Loop and shouldn't be used more than
83 * once. This must not be used within the WordPress Loop.
87 * @global WP_Query $wp_query Global WP_Query instance.
89 * @param string $query
90 * @return array List of posts
92 function query_posts($query) {
93 $GLOBALS['wp_query'] = new WP_Query();
94 return $GLOBALS['wp_query']->query($query);
98 * Destroy the previous query and set up a new query.
100 * This should be used after {@link query_posts()} and before another {@link
101 * query_posts()}. This will remove obscure bugs that occur when the previous
102 * wp_query object is not destroyed properly before another is set up.
106 * @global WP_Query $wp_query Global WP_Query instance.
107 * @global WP_Query $wp_the_query Copy of the global WP_Query instance created during wp_reset_query().
109 function wp_reset_query() {
110 $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
115 * After looping through a separate query, this function restores
116 * the $post global to the current post in the main query.
120 * @global WP_Query $wp_query Global WP_Query instance.
122 function wp_reset_postdata() {
125 if ( isset( $wp_query ) ) {
126 $wp_query->reset_postdata();
135 * Is the query for an existing archive page?
137 * Month, Year, Category, Author, Post Type archive...
141 * @global WP_Query $wp_query Global WP_Query instance.
145 function is_archive() {
148 if ( ! isset( $wp_query ) ) {
149 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
153 return $wp_query->is_archive();
157 * Is the query for an existing post type archive page?
161 * @global WP_Query $wp_query Global WP_Query instance.
163 * @param string|array $post_types Optional. Post type or array of posts types to check against.
166 function is_post_type_archive( $post_types = '' ) {
169 if ( ! isset( $wp_query ) ) {
170 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
174 return $wp_query->is_post_type_archive( $post_types );
178 * Is the query for an existing attachment page?
182 * @global WP_Query $wp_query Global WP_Query instance.
184 * @param int|string|array|object $attachment Attachment ID, title, slug, or array of such.
187 function is_attachment( $attachment = '' ) {
190 if ( ! isset( $wp_query ) ) {
191 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
195 return $wp_query->is_attachment( $attachment );
199 * Is the query for an existing author archive page?
201 * If the $author parameter is specified, this function will additionally
202 * check if the query is for one of the authors specified.
206 * @global WP_Query $wp_query Global WP_Query instance.
208 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
211 function is_author( $author = '' ) {
214 if ( ! isset( $wp_query ) ) {
215 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
219 return $wp_query->is_author( $author );
223 * Is the query for an existing category archive page?
225 * If the $category parameter is specified, this function will additionally
226 * check if the query is for one of the categories specified.
230 * @global WP_Query $wp_query Global WP_Query instance.
232 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
235 function is_category( $category = '' ) {
238 if ( ! isset( $wp_query ) ) {
239 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
243 return $wp_query->is_category( $category );
247 * Is the query for an existing tag archive page?
249 * If the $tag parameter is specified, this function will additionally
250 * check if the query is for one of the tags specified.
254 * @global WP_Query $wp_query Global WP_Query instance.
256 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
259 function is_tag( $tag = '' ) {
262 if ( ! isset( $wp_query ) ) {
263 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
267 return $wp_query->is_tag( $tag );
271 * Is the query for an existing taxonomy archive page?
273 * If the $taxonomy parameter is specified, this function will additionally
274 * check if the query is for that specific $taxonomy.
276 * If the $term parameter is specified in addition to the $taxonomy parameter,
277 * this function will additionally check if the query is for one of the terms
282 * @global WP_Query $wp_query Global WP_Query instance.
284 * @param string|array $taxonomy Optional. Taxonomy slug or slugs.
285 * @param int|string|array $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
288 function is_tax( $taxonomy = '', $term = '' ) {
291 if ( ! isset( $wp_query ) ) {
292 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
296 return $wp_query->is_tax( $taxonomy, $term );
300 * Whether the current URL is within the comments popup window.
304 * @global WP_Query $wp_query Global WP_Query instance.
308 function is_comments_popup() {
311 if ( ! isset( $wp_query ) ) {
312 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
316 return $wp_query->is_comments_popup();
320 * Is the query for an existing date archive?
324 * @global WP_Query $wp_query Global WP_Query instance.
331 if ( ! isset( $wp_query ) ) {
332 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
336 return $wp_query->is_date();
340 * Is the query for an existing day archive?
344 * @global WP_Query $wp_query Global WP_Query instance.
351 if ( ! isset( $wp_query ) ) {
352 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
356 return $wp_query->is_day();
360 * Is the query for a feed?
364 * @global WP_Query $wp_query Global WP_Query instance.
366 * @param string|array $feeds Optional feed types to check.
369 function is_feed( $feeds = '' ) {
372 if ( ! isset( $wp_query ) ) {
373 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
377 return $wp_query->is_feed( $feeds );
381 * Is the query for a comments feed?
385 * @global WP_Query $wp_query Global WP_Query instance.
389 function is_comment_feed() {
392 if ( ! isset( $wp_query ) ) {
393 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
397 return $wp_query->is_comment_feed();
401 * Is the query for the front page of the site?
403 * This is for what is displayed at your site's main URL.
405 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
407 * If you set a static page for the front page of your site, this function will return
408 * true when viewing that page.
410 * Otherwise the same as @see is_home()
414 * @global WP_Query $wp_query Global WP_Query instance.
416 * @return bool True, if front of site.
418 function is_front_page() {
421 if ( ! isset( $wp_query ) ) {
422 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
426 return $wp_query->is_front_page();
430 * Is the query for the blog homepage?
432 * This is the page which shows the time based blog content of your site.
434 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
436 * If you set a static page for the front page of your site, this function will return
437 * true only on the page you set as the "Posts page".
439 * @see is_front_page()
443 * @global WP_Query $wp_query Global WP_Query instance.
445 * @return bool True if blog view homepage.
450 if ( ! isset( $wp_query ) ) {
451 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
455 return $wp_query->is_home();
459 * Is the query for an existing month archive?
463 * @global WP_Query $wp_query Global WP_Query instance.
467 function is_month() {
470 if ( ! isset( $wp_query ) ) {
471 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
475 return $wp_query->is_month();
479 * Is the query for an existing single page?
481 * If the $page parameter is specified, this function will additionally
482 * check if the query is for one of the pages specified.
489 * @global WP_Query $wp_query Global WP_Query instance.
491 * @param int|string|array $page Optional. Page ID, title, slug, or array of such. Default empty.
492 * @return bool Whether the query is for an existing single page.
494 function is_page( $page = '' ) {
497 if ( ! isset( $wp_query ) ) {
498 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
502 return $wp_query->is_page( $page );
506 * Is the query for paged result and not for the first page?
510 * @global WP_Query $wp_query Global WP_Query instance.
514 function is_paged() {
517 if ( ! isset( $wp_query ) ) {
518 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
522 return $wp_query->is_paged();
526 * Is the query for a post or page preview?
530 * @global WP_Query $wp_query Global WP_Query instance.
534 function is_preview() {
537 if ( ! isset( $wp_query ) ) {
538 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
542 return $wp_query->is_preview();
546 * Is the query for the robots file?
550 * @global WP_Query $wp_query Global WP_Query instance.
554 function is_robots() {
557 if ( ! isset( $wp_query ) ) {
558 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
562 return $wp_query->is_robots();
566 * Is the query for a search?
570 * @global WP_Query $wp_query Global WP_Query instance.
574 function is_search() {
577 if ( ! isset( $wp_query ) ) {
578 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
582 return $wp_query->is_search();
586 * Is the query for an existing single post?
588 * Works for any post type, except attachments and pages
590 * If the $post parameter is specified, this function will additionally
591 * check if the query is for one of the Posts specified.
598 * @global WP_Query $wp_query Global WP_Query instance.
600 * @param int|string|array $post Optional. Post ID, title, slug, or array of such. Default empty.
601 * @return bool Whether the query is for an existing single post.
603 function is_single( $post = '' ) {
606 if ( ! isset( $wp_query ) ) {
607 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
611 return $wp_query->is_single( $post );
615 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
617 * If the $post_types parameter is specified, this function will additionally
618 * check if the query is for one of the Posts Types specified.
625 * @global WP_Query $wp_query Global WP_Query instance.
627 * @param string|array $post_types Optional. Post type or array of post types. Default empty.
628 * @return bool Whether the query is for an existing single post of any of the given post types.
630 function is_singular( $post_types = '' ) {
633 if ( ! isset( $wp_query ) ) {
634 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
638 return $wp_query->is_singular( $post_types );
642 * Is the query for a specific time?
646 * @global WP_Query $wp_query Global WP_Query instance.
653 if ( ! isset( $wp_query ) ) {
654 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
658 return $wp_query->is_time();
662 * Is the query for a trackback endpoint call?
666 * @global WP_Query $wp_query Global WP_Query instance.
670 function is_trackback() {
673 if ( ! isset( $wp_query ) ) {
674 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
678 return $wp_query->is_trackback();
682 * Is the query for an existing year archive?
686 * @global WP_Query $wp_query Global WP_Query instance.
693 if ( ! isset( $wp_query ) ) {
694 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
698 return $wp_query->is_year();
702 * Is the query a 404 (returns no results)?
706 * @global WP_Query $wp_query Global WP_Query instance.
713 if ( ! isset( $wp_query ) ) {
714 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
718 return $wp_query->is_404();
722 * Is the query for an embedded post?
726 * @global WP_Query $wp_query Global WP_Query instance.
728 * @return bool Whether we're in an embedded post or not.
730 function is_embed() {
733 if ( ! isset( $wp_query ) ) {
734 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
738 return $wp_query->is_embed();
742 * Is the query the main query?
746 * @global WP_Query $wp_query Global WP_Query instance.
750 function is_main_query() {
751 if ( 'pre_get_posts' === current_filter() ) {
753 /* translators: 1: pre_get_posts 2: WP_Query->is_main_query() 3: is_main_query() 4: link to codex is_main_query() page. */
754 __( 'In %1$s, use the %2$s method, not the %3$s function. See %4$s.' ),
755 '<code>pre_get_posts</code>',
756 '<code>WP_Query->is_main_query()</code>',
757 '<code>is_main_query()</code>',
758 __( 'https://codex.wordpress.org/Function_Reference/is_main_query' )
760 _doing_it_wrong( __FUNCTION__, $message, '3.7' );
764 return $wp_query->is_main_query();
768 * The Loop. Post loop control.
772 * Whether current WordPress query has results to loop over.
776 * @global WP_Query $wp_query Global WP_Query instance.
780 function have_posts() {
782 return $wp_query->have_posts();
786 * Whether the caller is in the Loop.
790 * @global WP_Query $wp_query Global WP_Query instance.
792 * @return bool True if caller is within loop, false if loop hasn't started or ended.
794 function in_the_loop() {
796 return $wp_query->in_the_loop;
800 * Rewind the loop posts.
804 * @global WP_Query $wp_query Global WP_Query instance.
806 function rewind_posts() {
808 $wp_query->rewind_posts();
812 * Iterate the post index in the loop.
816 * @global WP_Query $wp_query Global WP_Query instance.
818 function the_post() {
820 $wp_query->the_post();
828 * Whether there are comments to loop over.
832 * @global WP_Query $wp_query Global WP_Query instance.
836 function have_comments() {
838 return $wp_query->have_comments();
842 * Iterate comment index in the comment loop.
846 * @global WP_Query $wp_query Global WP_Query instance.
850 function the_comment() {
852 return $wp_query->the_comment();
860 * The WordPress Query class.
862 * @link https://codex.wordpress.org/Function_Reference/WP_Query Codex page.
869 * Query vars set by the user
878 * Query vars, after parsing
884 public $query_vars = array();
887 * Taxonomy query, as passed to get_tax_sql()
891 * @var object WP_Tax_Query
896 * Metadata query container
900 * @var object WP_Meta_Query
902 public $meta_query = false;
905 * Date query container
909 * @var object WP_Date_Query
911 public $date_query = false;
914 * Holds the data for a single object that is queried.
916 * Holds the contents of a post, page, category, attachment.
922 public $queried_object;
925 * The ID of the queried object.
931 public $queried_object_id;
934 * Get post database query.
952 * The amount of posts for the current query.
958 public $post_count = 0;
961 * Index of the current item in the loop.
967 public $current_post = -1;
970 * Whether the loop has started and the caller is in the loop.
976 public $in_the_loop = false;
988 * The list of comments for current post.
997 * The amount of comments for the posts.
1003 public $comment_count = 0;
1006 * The index of the comment in the comment loop.
1012 public $current_comment = -1;
1015 * Current comment ID.
1024 * The amount of found posts for the current query.
1026 * If limit clause was not used, equals $post_count.
1032 public $found_posts = 0;
1035 * The amount of pages.
1041 public $max_num_pages = 0;
1044 * The amount of comment pages.
1050 public $max_num_comment_pages = 0;
1053 * Set if query is single post.
1059 public $is_single = false;
1062 * Set if query is preview of blog.
1068 public $is_preview = false;
1071 * Set if query returns a page.
1077 public $is_page = false;
1080 * Set if query is an archive list.
1086 public $is_archive = false;
1089 * Set if query is part of a date.
1095 public $is_date = false;
1098 * Set if query contains a year.
1104 public $is_year = false;
1107 * Set if query contains a month.
1113 public $is_month = false;
1116 * Set if query contains a day.
1122 public $is_day = false;
1125 * Set if query contains time.
1131 public $is_time = false;
1134 * Set if query contains an author.
1140 public $is_author = false;
1143 * Set if query contains category.
1149 public $is_category = false;
1152 * Set if query contains tag.
1158 public $is_tag = false;
1161 * Set if query contains taxonomy.
1167 public $is_tax = false;
1170 * Set if query was part of a search result.
1176 public $is_search = false;
1179 * Set if query is feed display.
1185 public $is_feed = false;
1188 * Set if query is comment feed display.
1194 public $is_comment_feed = false;
1197 * Set if query is trackback.
1203 public $is_trackback = false;
1206 * Set if query is blog homepage.
1212 public $is_home = false;
1215 * Set if query couldn't found anything.
1221 public $is_404 = false;
1224 * Set if query is embed.
1230 public $is_embed = false;
1233 * Set if query is within comments popup window.
1239 public $is_comments_popup = false;
1242 * Set if query is paged
1248 public $is_paged = false;
1251 * Set if query is part of administration page.
1257 public $is_admin = false;
1260 * Set if query is an attachment.
1266 public $is_attachment = false;
1269 * Set if is single, is a page, or is an attachment.
1275 public $is_singular = false;
1278 * Set if query is for robots.
1284 public $is_robots = false;
1287 * Set if query contains posts.
1289 * Basically, the homepage if the option isn't set for the static homepage.
1295 public $is_posts_page = false;
1298 * Set if query is for a post type archive.
1304 public $is_post_type_archive = false;
1307 * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
1308 * whether we have to re-parse because something has changed
1314 private $query_vars_hash = false;
1317 * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
1318 * via pre_get_posts hooks.
1323 private $query_vars_changed = true;
1326 * Set if post thumbnails are cached
1332 public $thumbnails_cached = false;
1335 * Whether the term meta cache for matched posts has been primed.
1341 public $updated_term_meta_cache = false;
1344 * Whether the comment meta cache for matched posts has been primed.
1350 public $updated_comment_meta_cache = false;
1353 * Cached list of search stopwords.
1360 private $compat_fields = array( 'query_vars_hash', 'query_vars_changed' );
1362 private $compat_methods = array( 'init_query_flags', 'parse_tax_query' );
1365 * Resets query flags to false.
1367 * The query flags are what page info WordPress was able to figure out.
1372 private function init_query_flags() {
1373 $this->is_single = false;
1374 $this->is_preview = false;
1375 $this->is_page = false;
1376 $this->is_archive = false;
1377 $this->is_date = false;
1378 $this->is_year = false;
1379 $this->is_month = false;
1380 $this->is_day = false;
1381 $this->is_time = false;
1382 $this->is_author = false;
1383 $this->is_category = false;
1384 $this->is_tag = false;
1385 $this->is_tax = false;
1386 $this->is_search = false;
1387 $this->is_feed = false;
1388 $this->is_comment_feed = false;
1389 $this->is_trackback = false;
1390 $this->is_home = false;
1391 $this->is_404 = false;
1392 $this->is_comments_popup = false;
1393 $this->is_paged = false;
1394 $this->is_admin = false;
1395 $this->is_attachment = false;
1396 $this->is_singular = false;
1397 $this->is_robots = false;
1398 $this->is_posts_page = false;
1399 $this->is_post_type_archive = false;
1403 * Initiates object properties and sets default values.
1408 public function init() {
1409 unset($this->posts);
1410 unset($this->query);
1411 $this->query_vars = array();
1412 unset($this->queried_object);
1413 unset($this->queried_object_id);
1414 $this->post_count = 0;
1415 $this->current_post = -1;
1416 $this->in_the_loop = false;
1417 unset( $this->request );
1418 unset( $this->post );
1419 unset( $this->comments );
1420 unset( $this->comment );
1421 $this->comment_count = 0;
1422 $this->current_comment = -1;
1423 $this->found_posts = 0;
1424 $this->max_num_pages = 0;
1425 $this->max_num_comment_pages = 0;
1427 $this->init_query_flags();
1431 * Reparse the query vars.
1436 public function parse_query_vars() {
1437 $this->parse_query();
1441 * Fills in the query variables, which do not exist within the parameter.
1446 * @param array $array Defined query variables.
1447 * @return array Complete query variables with undefined ones filled in empty.
1449 public function fill_query_vars($array) {
1490 foreach ( $keys as $key ) {
1491 if ( !isset($array[$key]) )
1495 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in', 'post_name__in',
1496 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
1497 'author__in', 'author__not_in' );
1499 foreach ( $array_keys as $key ) {
1500 if ( !isset($array[$key]) )
1501 $array[$key] = array();
1507 * Parse a query string and set query type booleans.
1510 * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
1511 * array key to `$orderby`.
1512 * @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
1513 * search terms, by prepending a hyphen.
1516 * @param string|array $query {
1517 * Optional. Array or string of Query parameters.
1519 * @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
1520 * @type int|string $author Author ID, or comma-separated list of IDs.
1521 * @type string $author_name User 'user_nicename'.
1522 * @type array $author__in An array of author IDs to query from.
1523 * @type array $author__not_in An array of author IDs not to query from.
1524 * @type bool $cache_results Whether to cache post information. Default true.
1525 * @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
1526 * @type array $category__and An array of category IDs (AND in).
1527 * @type array $category__in An array of category IDs (OR in, no children).
1528 * @type array $category__not_in An array of category IDs (NOT in).
1529 * @type string $category_name Use category slug (not name, this or any children).
1530 * @type int $comments_per_page The number of comments to return per page.
1531 * Default 'comments_per_page' option.
1532 * @type int|string $comments_popup Whether the query is within the comments popup. Default empty.
1533 * @type array $date_query An associative array of WP_Date_Query arguments.
1534 * {@see WP_Date_Query::__construct()}
1535 * @type int $day Day of the month. Default empty. Accepts numbers 1-31.
1536 * @type bool $exact Whether to search by exact keyword. Default false.
1537 * @type string|array $fields Which fields to return. Single field or all fields (string),
1538 * or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
1539 * Default all fields. Accepts 'ids', 'id=>parent'.
1540 * @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
1541 * @type int|bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
1542 * excludes stickies from 'post__in'. Accepts 1|true, 0|false.
1544 * @type int $m Combination YearMonth. Accepts any four-digit year and month
1545 * numbers 1-12. Default empty.
1546 * @type string $meta_compare Comparison operator to test the 'meta_value'.
1547 * @type string $meta_key Custom field key.
1548 * @type array $meta_query An associative array of WP_Meta_Query arguments.
1549 * {@see WP_Meta_Query->queries}
1550 * @type string $meta_value Custom field value.
1551 * @type int $meta_value_num Custom field value number.
1552 * @type int $menu_order The menu order of the posts.
1553 * @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
1554 * @type string $name Post slug.
1555 * @type bool $nopaging Show all posts (true) or paginate (false). Default false.
1556 * @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
1557 * performance. Default false.
1558 * @type int $offset The number of posts to offset before retrieval.
1559 * @type string $order Designates ascending or descending order of posts. Default 'DESC'.
1560 * Accepts 'ASC', 'DESC'.
1561 * @type string|array $orderby Sort retrieved posts by parameter. One or more options may be
1562 * passed. To use 'meta_value', or 'meta_value_num',
1563 * 'meta_key=keyname' must be also be defined. To sort by a
1564 * specific `$meta_query` clause, use that clause's array key.
1565 * Default 'date'. Accepts 'none', 'name', 'author', 'date',
1566 * 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand',
1567 * 'comment_count', 'meta_value', 'meta_value_num', 'post__in',
1568 * and the array keys of `$meta_query`.
1569 * @type int $p Post ID.
1570 * @type int $page Show the number of posts that would show up on page X of a
1571 * static front page.
1572 * @type int $paged The number of the current page.
1573 * @type int $page_id Page ID.
1574 * @type string $pagename Page slug.
1575 * @type string $perm Show posts if user has the appropriate capability.
1576 * @type array $post__in An array of post IDs to retrieve, sticky posts will be included
1577 * @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
1578 * @type array $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
1579 * separated IDs will NOT work.
1580 * @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
1582 * @type array $post_parent__in An array containing parent page IDs to query child pages from.
1583 * @type array $post_parent__not_in An array containing parent page IDs not to query child pages from.
1584 * @type string|array $post_type A post type slug (string) or array of post type slugs.
1585 * Default 'any' if using 'tax_query'.
1586 * @type string|array $post_status A post status (string) or array of post statuses.
1587 * @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
1588 * @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
1589 * 'posts_per_page' when is_archive(), or is_search() are true.
1590 * @type array $post_name__in An array of post slugs that results must match.
1591 * @type string $s Search keyword(s). Prepending a term with a hyphen will
1592 * exclude posts matching that term. Eg, 'pillow -sofa' will
1593 * return posts containing 'pillow' but not 'sofa'.
1594 * @type int $second Second of the minute. Default empty. Accepts numbers 0-60.
1595 * @type bool $sentence Whether to search by phrase. Default false.
1596 * @type bool $suppress_filters Whether to suppress filters. Default false.
1597 * @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
1598 * @type array $tag__and An array of tag ids (AND in).
1599 * @type array $tag__in An array of tag ids (OR in).
1600 * @type array $tag__not_in An array of tag ids (NOT in).
1601 * @type int $tag_id Tag id or comma-separated list of IDs.
1602 * @type array $tag_slug__and An array of tag slugs (AND in).
1603 * @type array $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
1604 * true. Note: a string of comma-separated IDs will NOT work.
1605 * @type array $tax_query An associative array of WP_Tax_Query arguments.
1606 * {@see WP_Tax_Query->queries}
1607 * @type string $title Post title.
1608 * @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
1609 * @type bool $update_post_term_cache Whether to update the post term cache. Default true.
1610 * @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
1611 * @type int $year The four-digit year. Default empty. Accepts any four-digit year.
1614 public function parse_query( $query = '' ) {
1615 if ( ! empty( $query ) ) {
1617 $this->query = $this->query_vars = wp_parse_args( $query );
1618 } elseif ( ! isset( $this->query ) ) {
1619 $this->query = $this->query_vars;
1622 $this->query_vars = $this->fill_query_vars($this->query_vars);
1623 $qv = &$this->query_vars;
1624 $this->query_vars_changed = true;
1626 if ( ! empty($qv['robots']) )
1627 $this->is_robots = true;
1629 $qv['p'] = absint($qv['p']);
1630 $qv['page_id'] = absint($qv['page_id']);
1631 $qv['year'] = absint($qv['year']);
1632 $qv['monthnum'] = absint($qv['monthnum']);
1633 $qv['day'] = absint($qv['day']);
1634 $qv['w'] = absint($qv['w']);
1635 $qv['m'] = preg_replace( '|[^0-9]|', '', $qv['m'] );
1636 $qv['paged'] = absint($qv['paged']);
1637 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1638 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
1639 $qv['pagename'] = trim( $qv['pagename'] );
1640 $qv['name'] = trim( $qv['name'] );
1641 $qv['title'] = trim( $qv['title'] );
1642 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1643 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1644 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1645 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
1647 // Fairly insane upper bound for search string lengths.
1648 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
1652 // Compat. Map subpost to attachment.
1653 if ( '' != $qv['subpost'] )
1654 $qv['attachment'] = $qv['subpost'];
1655 if ( '' != $qv['subpost_id'] )
1656 $qv['attachment_id'] = $qv['subpost_id'];
1658 $qv['attachment_id'] = absint($qv['attachment_id']);
1660 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1661 $this->is_single = true;
1662 $this->is_attachment = true;
1663 } elseif ( '' != $qv['name'] ) {
1664 $this->is_single = true;
1665 } elseif ( $qv['p'] ) {
1666 $this->is_single = true;
1667 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1668 // If year, month, day, hour, minute, and second are set, a single
1669 // post is being queried.
1670 $this->is_single = true;
1671 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1672 $this->is_page = true;
1673 $this->is_single = false;
1675 // Look for archive queries. Dates, categories, authors, search, post type archives.
1677 if ( isset( $this->query['s'] ) ) {
1678 $this->is_search = true;
1681 if ( '' !== $qv['second'] ) {
1682 $this->is_time = true;
1683 $this->is_date = true;
1686 if ( '' !== $qv['minute'] ) {
1687 $this->is_time = true;
1688 $this->is_date = true;
1691 if ( '' !== $qv['hour'] ) {
1692 $this->is_time = true;
1693 $this->is_date = true;
1697 if ( ! $this->is_date ) {
1698 $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
1699 if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
1700 $qv['error'] = '404';
1702 $this->is_day = true;
1703 $this->is_date = true;
1708 if ( $qv['monthnum'] ) {
1709 if ( ! $this->is_date ) {
1710 if ( 12 < $qv['monthnum'] ) {
1711 $qv['error'] = '404';
1713 $this->is_month = true;
1714 $this->is_date = true;
1719 if ( $qv['year'] ) {
1720 if ( ! $this->is_date ) {
1721 $this->is_year = true;
1722 $this->is_date = true;
1727 $this->is_date = true;
1728 if ( strlen($qv['m']) > 9 ) {
1729 $this->is_time = true;
1730 } elseif ( strlen( $qv['m'] ) > 7 ) {
1731 $this->is_day = true;
1732 } elseif ( strlen( $qv['m'] ) > 5 ) {
1733 $this->is_month = true;
1735 $this->is_year = true;
1739 if ( '' != $qv['w'] ) {
1740 $this->is_date = true;
1743 $this->query_vars_hash = false;
1744 $this->parse_tax_query( $qv );
1746 foreach ( $this->tax_query->queries as $tax_query ) {
1747 if ( ! is_array( $tax_query ) ) {
1751 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
1752 switch ( $tax_query['taxonomy'] ) {
1754 $this->is_category = true;
1757 $this->is_tag = true;
1760 $this->is_tax = true;
1764 unset( $tax_query );
1766 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1767 $this->is_author = false;
1769 $this->is_author = true;
1772 if ( '' != $qv['author_name'] )
1773 $this->is_author = true;
1775 if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
1776 $post_type_obj = get_post_type_object( $qv['post_type'] );
1777 if ( ! empty( $post_type_obj->has_archive ) )
1778 $this->is_post_type_archive = true;
1781 if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
1782 $this->is_archive = true;
1785 if ( '' != $qv['feed'] )
1786 $this->is_feed = true;
1788 if ( '' != $qv['tb'] )
1789 $this->is_trackback = true;
1791 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
1792 $this->is_paged = true;
1794 if ( '' != $qv['comments_popup'] )
1795 $this->is_comments_popup = true;
1797 // if we're previewing inside the write screen
1798 if ( '' != $qv['preview'] )
1799 $this->is_preview = true;
1802 $this->is_admin = true;
1804 if ( false !== strpos($qv['feed'], 'comments-') ) {
1805 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1806 $qv['withcomments'] = 1;
1809 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1811 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1812 $this->is_comment_feed = true;
1814 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup || $this->is_robots ) )
1815 $this->is_home = true;
1817 // Correct is_* for page_on_front and page_for_posts
1818 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1819 $_query = wp_parse_args($this->query);
1820 // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
1821 if ( isset($_query['pagename']) && '' == $_query['pagename'] )
1822 unset($_query['pagename']);
1823 if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
1824 $this->is_page = true;
1825 $this->is_home = false;
1826 $qv['page_id'] = get_option('page_on_front');
1827 // Correct <!--nextpage--> for page_on_front
1828 if ( !empty($qv['paged']) ) {
1829 $qv['page'] = $qv['paged'];
1830 unset($qv['paged']);
1835 if ( '' != $qv['pagename'] ) {
1836 $this->queried_object = get_page_by_path( $qv['pagename'] );
1838 if ( $this->queried_object && 'attachment' == $this->queried_object->post_type ) {
1839 if ( preg_match( "/^[^%]*%(?:postname)%/", get_option( 'permalink_structure' ) ) ) {
1840 // See if we also have a post with the same slug
1841 $post = get_page_by_path( $qv['pagename'], OBJECT, 'post' );
1843 $this->queried_object = $post;
1844 $this->is_page = false;
1845 $this->is_single = true;
1850 if ( ! empty( $this->queried_object ) ) {
1851 $this->queried_object_id = (int) $this->queried_object->ID;
1853 unset( $this->queried_object );
1856 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1857 $this->is_page = false;
1858 $this->is_home = true;
1859 $this->is_posts_page = true;
1863 if ( $qv['page_id'] ) {
1864 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1865 $this->is_page = false;
1866 $this->is_home = true;
1867 $this->is_posts_page = true;
1871 if ( !empty($qv['post_type']) ) {
1872 if ( is_array($qv['post_type']) )
1873 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1875 $qv['post_type'] = sanitize_key($qv['post_type']);
1878 if ( ! empty( $qv['post_status'] ) ) {
1879 if ( is_array( $qv['post_status'] ) )
1880 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1882 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1885 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1886 $this->is_comment_feed = false;
1888 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1889 // Done correcting is_* for page_on_front and page_for_posts
1891 if ( '404' == $qv['error'] )
1894 $this->is_embed = isset( $qv['embed'] ) && ( $this->is_singular || $this->is_404 );
1896 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1897 $this->query_vars_changed = false;
1900 * Fires after the main query vars have been parsed.
1904 * @param WP_Query &$this The WP_Query instance (passed by reference).
1906 do_action_ref_array( 'parse_query', array( &$this ) );
1910 * Parses various taxonomy related query vars.
1912 * For BC, this method is not marked as protected. See [28987].
1917 * @param array &$q The query variables
1919 public function parse_tax_query( &$q ) {
1920 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1921 $tax_query = $q['tax_query'];
1923 $tax_query = array();
1926 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1927 $tax_query[] = array(
1928 'taxonomy' => $q['taxonomy'],
1929 'terms' => array( $q['term'] ),
1934 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1935 if ( 'post_tag' == $taxonomy )
1936 continue; // Handled further down in the $q['tag'] block
1938 if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1939 $tax_query_defaults = array(
1940 'taxonomy' => $taxonomy,
1944 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1945 $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1948 $term = $q[$t->query_var];
1950 if ( is_array( $term ) ) {
1951 $term = implode( ',', $term );
1954 if ( strpos($term, '+') !== false ) {
1955 $terms = preg_split( '/[+]+/', $term );
1956 foreach ( $terms as $term ) {
1957 $tax_query[] = array_merge( $tax_query_defaults, array(
1958 'terms' => array( $term )
1962 $tax_query[] = array_merge( $tax_query_defaults, array(
1963 'terms' => preg_split( '/[,]+/', $term )
1969 // If querystring 'cat' is an array, implode it.
1970 if ( is_array( $q['cat'] ) ) {
1971 $q['cat'] = implode( ',', $q['cat'] );
1975 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1976 $cat_in = $cat_not_in = array();
1978 $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1979 $cat_array = array_map( 'intval', $cat_array );
1980 $q['cat'] = implode( ',', $cat_array );
1982 foreach ( $cat_array as $cat ) {
1986 $cat_not_in[] = abs( $cat );
1989 if ( ! empty( $cat_in ) ) {
1990 $tax_query[] = array(
1991 'taxonomy' => 'category',
1993 'field' => 'term_id',
1994 'include_children' => true
1998 if ( ! empty( $cat_not_in ) ) {
1999 $tax_query[] = array(
2000 'taxonomy' => 'category',
2001 'terms' => $cat_not_in,
2002 'field' => 'term_id',
2003 'operator' => 'NOT IN',
2004 'include_children' => true
2007 unset( $cat_array, $cat_in, $cat_not_in );
2010 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
2011 $q['category__and'] = (array) $q['category__and'];
2012 if ( ! isset( $q['category__in'] ) )
2013 $q['category__in'] = array();
2014 $q['category__in'][] = absint( reset( $q['category__and'] ) );
2015 unset( $q['category__and'] );
2018 if ( ! empty( $q['category__in'] ) ) {
2019 $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
2020 $tax_query[] = array(
2021 'taxonomy' => 'category',
2022 'terms' => $q['category__in'],
2023 'field' => 'term_id',
2024 'include_children' => false
2028 if ( ! empty($q['category__not_in']) ) {
2029 $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
2030 $tax_query[] = array(
2031 'taxonomy' => 'category',
2032 'terms' => $q['category__not_in'],
2033 'operator' => 'NOT IN',
2034 'include_children' => false
2038 if ( ! empty($q['category__and']) ) {
2039 $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
2040 $tax_query[] = array(
2041 'taxonomy' => 'category',
2042 'terms' => $q['category__and'],
2043 'field' => 'term_id',
2044 'operator' => 'AND',
2045 'include_children' => false
2049 // If querystring 'tag' is array, implode it.
2050 if ( is_array( $q['tag'] ) ) {
2051 $q['tag'] = implode( ',', $q['tag'] );
2055 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
2056 if ( strpos($q['tag'], ',') !== false ) {
2057 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
2058 foreach ( (array) $tags as $tag ) {
2059 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
2060 $q['tag_slug__in'][] = $tag;
2062 } elseif ( preg_match('/[+\r\n\t ]+/', $q['tag'] ) || ! empty( $q['cat'] ) ) {
2063 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
2064 foreach ( (array) $tags as $tag ) {
2065 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
2066 $q['tag_slug__and'][] = $tag;
2069 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
2070 $q['tag_slug__in'][] = $q['tag'];
2074 if ( !empty($q['tag_id']) ) {
2075 $q['tag_id'] = absint( $q['tag_id'] );
2076 $tax_query[] = array(
2077 'taxonomy' => 'post_tag',
2078 'terms' => $q['tag_id']
2082 if ( !empty($q['tag__in']) ) {
2083 $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
2084 $tax_query[] = array(
2085 'taxonomy' => 'post_tag',
2086 'terms' => $q['tag__in']
2090 if ( !empty($q['tag__not_in']) ) {
2091 $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
2092 $tax_query[] = array(
2093 'taxonomy' => 'post_tag',
2094 'terms' => $q['tag__not_in'],
2095 'operator' => 'NOT IN'
2099 if ( !empty($q['tag__and']) ) {
2100 $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
2101 $tax_query[] = array(
2102 'taxonomy' => 'post_tag',
2103 'terms' => $q['tag__and'],
2108 if ( !empty($q['tag_slug__in']) ) {
2109 $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
2110 $tax_query[] = array(
2111 'taxonomy' => 'post_tag',
2112 'terms' => $q['tag_slug__in'],
2117 if ( !empty($q['tag_slug__and']) ) {
2118 $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
2119 $tax_query[] = array(
2120 'taxonomy' => 'post_tag',
2121 'terms' => $q['tag_slug__and'],
2127 $this->tax_query = new WP_Tax_Query( $tax_query );
2130 * Fires after taxonomy-related query vars have been parsed.
2134 * @param WP_Query $this The WP_Query instance.
2136 do_action( 'parse_tax_query', $this );
2140 * Generate SQL for the WHERE clause based on passed search terms.
2144 * @global wpdb $wpdb WordPress database abstraction object.
2146 * @param array $q Query variables.
2147 * @return string WHERE clause.
2149 protected function parse_search( &$q ) {
2154 // added slashes screw with quote grouping when done early, so done later
2155 $q['s'] = stripslashes( $q['s'] );
2156 if ( empty( $_GET['s'] ) && $this->is_main_query() )
2157 $q['s'] = urldecode( $q['s'] );
2158 // there are no line breaks in <input /> fields
2159 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
2160 $q['search_terms_count'] = 1;
2161 if ( ! empty( $q['sentence'] ) ) {
2162 $q['search_terms'] = array( $q['s'] );
2164 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
2165 $q['search_terms_count'] = count( $matches[0] );
2166 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
2167 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
2168 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
2169 $q['search_terms'] = array( $q['s'] );
2171 $q['search_terms'] = array( $q['s'] );
2175 $n = ! empty( $q['exact'] ) ? '' : '%';
2177 $q['search_orderby_title'] = array();
2178 foreach ( $q['search_terms'] as $term ) {
2179 // Terms prefixed with '-' should be excluded.
2180 $include = '-' !== substr( $term, 0, 1 );
2185 $like_op = 'NOT LIKE';
2187 $term = substr( $term, 1 );
2190 if ( $n && $include ) {
2191 $like = '%' . $wpdb->esc_like( $term ) . '%';
2192 $q['search_orderby_title'][] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like );
2195 $like = $n . $wpdb->esc_like( $term ) . $n;
2196 $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title $like_op %s) $andor_op ($wpdb->posts.post_content $like_op %s))", $like, $like );
2197 $searchand = ' AND ';
2200 if ( ! empty( $search ) ) {
2201 $search = " AND ({$search}) ";
2202 if ( ! is_user_logged_in() )
2203 $search .= " AND ($wpdb->posts.post_password = '') ";
2210 * Check if the terms are suitable for searching.
2212 * Uses an array of stopwords (terms) that are excluded from the separate
2213 * term matching when searching for posts. The list of English stopwords is
2214 * the approximate search engines list, and is translatable.
2218 * @param array $terms Terms to check.
2219 * @return array Terms that are not stopwords.
2221 protected function parse_search_terms( $terms ) {
2222 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
2225 $stopwords = $this->get_search_stopwords();
2227 foreach ( $terms as $term ) {
2228 // keep before/after spaces when term is for exact match
2229 if ( preg_match( '/^".+"$/', $term ) )
2230 $term = trim( $term, "\"'" );
2232 $term = trim( $term, "\"' " );
2234 // Avoid single A-Z.
2235 if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z]$/i', $term ) ) )
2238 if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
2248 * Retrieve stopwords used when parsing search terms.
2252 * @return array Stopwords.
2254 protected function get_search_stopwords() {
2255 if ( isset( $this->stopwords ) )
2256 return $this->stopwords;
2258 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
2259 * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
2260 * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
2262 $words = explode( ',', _x( 'about,an,are,as,at,be,by,com,for,from,how,in,is,it,of,on,or,that,the,this,to,was,what,when,where,who,will,with,www',
2263 'Comma-separated list of search stopwords in your language' ) );
2265 $stopwords = array();
2266 foreach ( $words as $word ) {
2267 $word = trim( $word, "\r\n\t " );
2269 $stopwords[] = $word;
2273 * Filter stopwords used when parsing search terms.
2277 * @param array $stopwords Stopwords.
2279 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
2280 return $this->stopwords;
2284 * Generate SQL for the ORDER BY condition based on passed search terms.
2286 * @global wpdb $wpdb WordPress database abstraction object.
2288 * @param array $q Query variables.
2289 * @return string ORDER BY clause.
2291 protected function parse_search_order( &$q ) {
2294 if ( $q['search_terms_count'] > 1 ) {
2295 $num_terms = count( $q['search_orderby_title'] );
2297 // If the search terms contain negative queries, don't bother ordering by sentence matches.
2299 if ( ! preg_match( '/(?:\s|^)\-/', $q['s'] ) ) {
2300 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
2303 $search_orderby = '';
2305 // sentence match in 'post_title'
2307 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_title LIKE %s THEN 1 ", $like );
2310 // sanity limit, sort as sentence when more than 6 terms
2311 // (few searches are longer than 6 terms and most titles are not)
2312 if ( $num_terms < 7 ) {
2313 // all words in title
2314 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
2315 // any word in title, not needed when $num_terms == 1
2316 if ( $num_terms > 1 )
2317 $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
2320 // sentence match in 'post_content'
2322 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 4 ", $like );
2325 if ( $search_orderby ) {
2326 $search_orderby = '(CASE ' . $search_orderby . 'ELSE 5 END)';
2329 // single word or sentence search
2330 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2333 return $search_orderby;
2337 * If the passed orderby value is allowed, convert the alias to a
2338 * properly-prefixed orderby value.
2343 * @global wpdb $wpdb WordPress database abstraction object.
2345 * @param string $orderby Alias for the field to order by.
2346 * @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
2348 protected function parse_orderby( $orderby ) {
2351 // Used to filter values.
2352 $allowed_keys = array(
2353 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2354 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2355 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2358 $primary_meta_key = '';
2359 $primary_meta_query = false;
2360 $meta_clauses = $this->meta_query->get_clauses();
2361 if ( ! empty( $meta_clauses ) ) {
2362 $primary_meta_query = reset( $meta_clauses );
2364 if ( ! empty( $primary_meta_query['key'] ) ) {
2365 $primary_meta_key = $primary_meta_query['key'];
2366 $allowed_keys[] = $primary_meta_key;
2369 $allowed_keys[] = 'meta_value';
2370 $allowed_keys[] = 'meta_value_num';
2371 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
2374 if ( ! in_array( $orderby, $allowed_keys, true ) ) {
2378 switch ( $orderby ) {
2383 case 'post_modified':
2388 case 'comment_count':
2389 $orderby_clause = "$wpdb->posts.{$orderby}";
2392 $orderby_clause = 'RAND()';
2394 case $primary_meta_key:
2396 if ( ! empty( $primary_meta_query['type'] ) ) {
2397 $orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
2399 $orderby_clause = "{$primary_meta_query['alias']}.meta_value";
2402 case 'meta_value_num':
2403 $orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
2406 if ( array_key_exists( $orderby, $meta_clauses ) ) {
2407 // $orderby corresponds to a meta_query clause.
2408 $meta_clause = $meta_clauses[ $orderby ];
2409 $orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
2411 // Default: order by post field.
2412 $orderby_clause = "$wpdb->posts.post_" . sanitize_key( $orderby );
2418 return $orderby_clause;
2422 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2427 * @param string $order The 'order' query variable.
2428 * @return string The sanitized 'order' query variable.
2430 protected function parse_order( $order ) {
2431 if ( ! is_string( $order ) || empty( $order ) ) {
2435 if ( 'ASC' === strtoupper( $order ) ) {
2443 * Sets the 404 property and saves whether query is feed.
2448 public function set_404() {
2449 $is_feed = $this->is_feed;
2451 $this->init_query_flags();
2452 $this->is_404 = true;
2454 $this->is_feed = $is_feed;
2458 * Retrieve query variable.
2461 * @since 3.9.0 The `$default` argument was introduced.
2465 * @param string $query_var Query variable key.
2466 * @param mixed $default Optional. Value to return if the query variable is not set. Default empty.
2467 * @return mixed Contents of the query variable.
2469 public function get( $query_var, $default = '' ) {
2470 if ( isset( $this->query_vars[ $query_var ] ) ) {
2471 return $this->query_vars[ $query_var ];
2478 * Set query variable.
2483 * @param string $query_var Query variable key.
2484 * @param mixed $value Query variable value.
2486 public function set($query_var, $value) {
2487 $this->query_vars[$query_var] = $value;
2491 * Retrieve the posts based on query variables.
2493 * There are a few filters and actions that can be used to modify the post
2499 * @global wpdb $wpdb WordPress database abstraction object.
2501 * @return array List of posts.
2503 public function get_posts() {
2506 $this->parse_query();
2509 * Fires after the query variable object is created, but before the actual query is run.
2511 * Note: If using conditional tags, use the method versions within the passed instance
2512 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2513 * like is_main_query() test against the global $wp_query instance, not the passed one.
2517 * @param WP_Query &$this The WP_Query instance (passed by reference).
2519 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2522 $q = &$this->query_vars;
2524 // Fill again in case pre_get_posts unset some vars.
2525 $q = $this->fill_query_vars($q);
2528 $this->meta_query = new WP_Meta_Query();
2529 $this->meta_query->parse_query_vars( $q );
2531 // Set a flag if a pre_get_posts hook changed the query vars.
2532 $hash = md5( serialize( $this->query_vars ) );
2533 if ( $hash != $this->query_vars_hash ) {
2534 $this->query_vars_changed = true;
2535 $this->query_vars_hash = $hash;
2539 // First let's clear some variables
2542 $whichmimetype = '';
2548 $post_status_join = false;
2551 if ( isset( $q['caller_get_posts'] ) ) {
2552 _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2553 if ( !isset( $q['ignore_sticky_posts'] ) )
2554 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2557 if ( !isset( $q['ignore_sticky_posts'] ) )
2558 $q['ignore_sticky_posts'] = false;
2560 if ( !isset($q['suppress_filters']) )
2561 $q['suppress_filters'] = false;
2563 if ( !isset($q['cache_results']) ) {
2564 if ( wp_using_ext_object_cache() )
2565 $q['cache_results'] = false;
2567 $q['cache_results'] = true;
2570 if ( !isset($q['update_post_term_cache']) )
2571 $q['update_post_term_cache'] = true;
2573 if ( !isset($q['update_post_meta_cache']) )
2574 $q['update_post_meta_cache'] = true;
2576 if ( !isset($q['post_type']) ) {
2577 if ( $this->is_search )
2578 $q['post_type'] = 'any';
2580 $q['post_type'] = '';
2582 $post_type = $q['post_type'];
2583 if ( empty( $q['posts_per_page'] ) ) {
2584 $q['posts_per_page'] = get_option( 'posts_per_page' );
2586 if ( isset($q['showposts']) && $q['showposts'] ) {
2587 $q['showposts'] = (int) $q['showposts'];
2588 $q['posts_per_page'] = $q['showposts'];
2590 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2591 $q['posts_per_page'] = $q['posts_per_archive_page'];
2592 if ( !isset($q['nopaging']) ) {
2593 if ( $q['posts_per_page'] == -1 ) {
2594 $q['nopaging'] = true;
2596 $q['nopaging'] = false;
2600 if ( $this->is_feed ) {
2601 // This overrides posts_per_page.
2602 if ( ! empty( $q['posts_per_rss'] ) ) {
2603 $q['posts_per_page'] = $q['posts_per_rss'];
2605 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2607 $q['nopaging'] = false;
2609 $q['posts_per_page'] = (int) $q['posts_per_page'];
2610 if ( $q['posts_per_page'] < -1 )
2611 $q['posts_per_page'] = abs($q['posts_per_page']);
2612 elseif ( $q['posts_per_page'] == 0 )
2613 $q['posts_per_page'] = 1;
2615 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2616 $q['comments_per_page'] = get_option('comments_per_page');
2618 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2619 $this->is_page = true;
2620 $this->is_home = false;
2621 $q['page_id'] = get_option('page_on_front');
2624 if ( isset($q['page']) ) {
2625 $q['page'] = trim($q['page'], '/');
2626 $q['page'] = absint($q['page']);
2629 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2630 if ( isset($q['no_found_rows']) )
2631 $q['no_found_rows'] = (bool) $q['no_found_rows'];
2633 $q['no_found_rows'] = false;
2635 switch ( $q['fields'] ) {
2637 $fields = "$wpdb->posts.ID";
2640 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2643 $fields = "$wpdb->posts.*";
2646 if ( '' !== $q['menu_order'] )
2647 $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2649 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2651 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2652 if ( strlen($q['m']) > 5 )
2653 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2654 if ( strlen($q['m']) > 7 )
2655 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2656 if ( strlen($q['m']) > 9 )
2657 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2658 if ( strlen($q['m']) > 11 )
2659 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2660 if ( strlen($q['m']) > 13 )
2661 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2664 // Handle the other individual date parameters
2665 $date_parameters = array();
2667 if ( '' !== $q['hour'] )
2668 $date_parameters['hour'] = $q['hour'];
2670 if ( '' !== $q['minute'] )
2671 $date_parameters['minute'] = $q['minute'];
2673 if ( '' !== $q['second'] )
2674 $date_parameters['second'] = $q['second'];
2677 $date_parameters['year'] = $q['year'];
2679 if ( $q['monthnum'] )
2680 $date_parameters['monthnum'] = $q['monthnum'];
2683 $date_parameters['week'] = $q['w'];
2686 $date_parameters['day'] = $q['day'];
2688 if ( $date_parameters ) {
2689 $date_query = new WP_Date_Query( array( $date_parameters ) );
2690 $where .= $date_query->get_sql();
2692 unset( $date_parameters, $date_query );
2694 // Handle complex date queries
2695 if ( ! empty( $q['date_query'] ) ) {
2696 $this->date_query = new WP_Date_Query( $q['date_query'] );
2697 $where .= $this->date_query->get_sql();
2701 // If we've got a post_type AND it's not "any" post_type.
2702 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2703 foreach ( (array)$q['post_type'] as $_post_type ) {
2704 $ptype_obj = get_post_type_object($_post_type);
2705 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2708 if ( ! $ptype_obj->hierarchical ) {
2709 // Non-hierarchical post types can directly use 'name'.
2710 $q['name'] = $q[ $ptype_obj->query_var ];
2712 // Hierarchical post types will operate through 'pagename'.
2713 $q['pagename'] = $q[ $ptype_obj->query_var ];
2717 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2723 if ( '' !== $q['title'] ) {
2724 $where .= $wpdb->prepare( " AND $wpdb->posts.post_title = %s", stripslashes( $q['title'] ) );
2727 // Parameters related to 'post_name'.
2728 if ( '' != $q['name'] ) {
2729 $q['name'] = sanitize_title_for_query( $q['name'] );
2730 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2731 } elseif ( '' != $q['pagename'] ) {
2732 if ( isset($this->queried_object_id) ) {
2733 $reqpage = $this->queried_object_id;
2735 if ( 'page' != $q['post_type'] ) {
2736 foreach ( (array)$q['post_type'] as $_post_type ) {
2737 $ptype_obj = get_post_type_object($_post_type);
2738 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2741 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2747 $reqpage = get_page_by_path($q['pagename']);
2749 if ( !empty($reqpage) )
2750 $reqpage = $reqpage->ID;
2755 $page_for_posts = get_option('page_for_posts');
2756 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2757 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2758 $q['name'] = $q['pagename'];
2759 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2760 $reqpage_obj = get_post( $reqpage );
2761 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2762 $this->is_attachment = true;
2763 $post_type = $q['post_type'] = 'attachment';
2764 $this->is_page = true;
2765 $q['attachment_id'] = $reqpage;
2768 } elseif ( '' != $q['attachment'] ) {
2769 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2770 $q['name'] = $q['attachment'];
2771 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2772 } elseif ( is_array( $q['post_name__in'] ) && ! empty( $q['post_name__in'] ) ) {
2773 $q['post_name__in'] = array_map( 'sanitize_title_for_query', $q['post_name__in'] );
2774 $where .= " AND $wpdb->posts.post_name IN ('" . implode( "' ,'", $q['post_name__in'] ) . "')";
2777 if ( intval($q['comments_popup']) )
2778 $q['p'] = absint($q['comments_popup']);
2780 // If an attachment is requested by number, let it supersede any post number.
2781 if ( $q['attachment_id'] )
2782 $q['p'] = absint($q['attachment_id']);
2784 // If a post number is specified, load that post
2786 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2787 } elseif ( $q['post__in'] ) {
2788 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2789 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2790 } elseif ( $q['post__not_in'] ) {
2791 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
2792 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2795 if ( is_numeric( $q['post_parent'] ) ) {
2796 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2797 } elseif ( $q['post_parent__in'] ) {
2798 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2799 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2800 } elseif ( $q['post_parent__not_in'] ) {
2801 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
2802 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2805 if ( $q['page_id'] ) {
2806 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2807 $q['p'] = $q['page_id'];
2808 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2812 // If a search pattern is specified, load the posts that match.
2813 if ( ! empty( $q['s'] ) ) {
2814 $search = $this->parse_search( $q );
2818 * Filter the search SQL that is used in the WHERE clause of WP_Query.
2822 * @param string $search Search SQL for WHERE clause.
2823 * @param WP_Query $this The current WP_Query object.
2825 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2828 if ( !$this->is_singular ) {
2829 $this->parse_tax_query( $q );
2831 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2833 $join .= $clauses['join'];
2834 $where .= $clauses['where'];
2837 if ( $this->is_tax ) {
2838 if ( empty($post_type) ) {
2839 // Do a fully inclusive search for currently registered post types of queried taxonomies
2840 $post_type = array();
2841 $taxonomies = array_keys( $this->tax_query->queried_terms );
2842 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2843 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2844 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2849 elseif ( count( $post_type ) == 1 )
2850 $post_type = $post_type[0];
2852 $post_status_join = true;
2853 } elseif ( in_array('attachment', (array) $post_type) ) {
2854 $post_status_join = true;
2859 * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2860 * 'category_name' vars are set for backward compatibility.
2862 if ( ! empty( $this->tax_query->queried_terms ) ) {
2865 * Set 'taxonomy', 'term', and 'term_id' to the
2866 * first taxonomy other than 'post_tag' or 'category'.
2868 if ( ! isset( $q['taxonomy'] ) ) {
2869 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2870 if ( empty( $queried_items['terms'][0] ) ) {
2874 if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2875 $q['taxonomy'] = $queried_taxonomy;
2877 if ( 'slug' === $queried_items['field'] ) {
2878 $q['term'] = $queried_items['terms'][0];
2880 $q['term_id'] = $queried_items['terms'][0];
2886 // 'cat', 'category_name', 'tag_id'
2887 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2888 if ( empty( $queried_items['terms'][0] ) ) {
2892 if ( 'category' === $queried_taxonomy ) {
2893 $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2895 $this->set( 'cat', $the_cat->term_id );
2896 $this->set( 'category_name', $the_cat->slug );
2901 if ( 'post_tag' === $queried_taxonomy ) {
2902 $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2904 $this->set( 'tag_id', $the_tag->term_id );
2911 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2912 $groupby = "{$wpdb->posts}.ID";
2915 // Author/user stuff
2917 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2918 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2919 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2920 foreach ( $authors as $author ) {
2921 $key = $author > 0 ? 'author__in' : 'author__not_in';
2922 $q[$key][] = abs( $author );
2924 $q['author'] = implode( ',', $authors );
2927 if ( ! empty( $q['author__not_in'] ) ) {
2928 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2929 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2930 } elseif ( ! empty( $q['author__in'] ) ) {
2931 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2932 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2935 // Author stuff for nice URLs
2937 if ( '' != $q['author_name'] ) {
2938 if ( strpos($q['author_name'], '/') !== false ) {
2939 $q['author_name'] = explode('/', $q['author_name']);
2940 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2941 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2943 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2946 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2947 $q['author'] = get_user_by('slug', $q['author_name']);
2949 $q['author'] = $q['author']->ID;
2950 $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2953 // MIME-Type stuff for attachment browsing
2955 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2956 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2958 $where .= $search . $whichauthor . $whichmimetype;
2960 if ( ! empty( $this->meta_query->queries ) ) {
2961 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
2962 $join .= $clauses['join'];
2963 $where .= $clauses['where'];
2966 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2967 if ( ! isset( $q['order'] ) ) {
2968 $q['order'] = $rand ? '' : 'DESC';
2970 $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2974 if ( empty( $q['orderby'] ) ) {
2976 * Boolean false or empty array blanks out ORDER BY,
2977 * while leaving the value unset or otherwise empty sets the default.
2979 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2982 $orderby = "$wpdb->posts.post_date " . $q['order'];
2984 } elseif ( 'none' == $q['orderby'] ) {
2986 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2987 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2988 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2989 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2991 $orderby_array = array();
2992 if ( is_array( $q['orderby'] ) ) {
2993 foreach ( $q['orderby'] as $_orderby => $order ) {
2994 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2995 $parsed = $this->parse_orderby( $orderby );
3001 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
3003 $orderby = implode( ', ', $orderby_array );
3006 $q['orderby'] = urldecode( $q['orderby'] );
3007 $q['orderby'] = addslashes_gpc( $q['orderby'] );
3009 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
3010 $parsed = $this->parse_orderby( $orderby );
3011 // Only allow certain values for safety.
3016 $orderby_array[] = $parsed;
3018 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
3020 if ( empty( $orderby ) ) {
3021 $orderby = "$wpdb->posts.post_date " . $q['order'];
3022 } elseif ( ! empty( $q['order'] ) ) {
3023 $orderby .= " {$q['order']}";
3028 // Order search results by relevance only when another "orderby" is not specified in the query.
3029 if ( ! empty( $q['s'] ) ) {
3030 $search_orderby = '';
3031 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
3032 $search_orderby = $this->parse_search_order( $q );
3035 * Filter the ORDER BY used when ordering search results.
3039 * @param string $search_orderby The ORDER BY clause.
3040 * @param WP_Query $this The current WP_Query instance.
3042 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
3043 if ( $search_orderby )
3044 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
3047 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
3048 $post_type_cap = 'multiple_post_type';
3050 if ( is_array( $post_type ) )
3051 $post_type = reset( $post_type );
3052 $post_type_object = get_post_type_object( $post_type );
3053 if ( empty( $post_type_object ) )
3054 $post_type_cap = $post_type;
3057 if ( isset( $q['post_password'] ) ) {
3058 $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
3059 if ( empty( $q['perm'] ) ) {
3060 $q['perm'] = 'readable';
3062 } elseif ( isset( $q['has_password'] ) ) {
3063 $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
3066 if ( 'any' == $post_type ) {
3067 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
3068 if ( empty( $in_search_post_types ) )
3069 $where .= ' AND 1=0 ';
3071 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')";
3072 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
3073 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
3074 } elseif ( ! empty( $post_type ) ) {
3075 $where .= " AND $wpdb->posts.post_type = '$post_type'";
3076 $post_type_object = get_post_type_object ( $post_type );
3077 } elseif ( $this->is_attachment ) {
3078 $where .= " AND $wpdb->posts.post_type = 'attachment'";
3079 $post_type_object = get_post_type_object ( 'attachment' );
3080 } elseif ( $this->is_page ) {
3081 $where .= " AND $wpdb->posts.post_type = 'page'";
3082 $post_type_object = get_post_type_object ( 'page' );
3084 $where .= " AND $wpdb->posts.post_type = 'post'";
3085 $post_type_object = get_post_type_object ( 'post' );
3088 $edit_cap = 'edit_post';
3089 $read_cap = 'read_post';
3091 if ( ! empty( $post_type_object ) ) {
3092 $edit_others_cap = $post_type_object->cap->edit_others_posts;
3093 $read_private_cap = $post_type_object->cap->read_private_posts;
3095 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
3096 $read_private_cap = 'read_private_' . $post_type_cap . 's';
3099 $user_id = get_current_user_id();
3101 $q_status = array();
3102 if ( ! empty( $q['post_status'] ) ) {
3103 $statuswheres = array();
3104 $q_status = $q['post_status'];
3105 if ( ! is_array( $q_status ) )
3106 $q_status = explode(',', $q_status);
3107 $r_status = array();
3108 $p_status = array();
3109 $e_status = array();
3110 if ( in_array( 'any', $q_status ) ) {
3111 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
3112 if ( ! in_array( $status, $q_status ) ) {
3113 $e_status[] = "$wpdb->posts.post_status <> '$status'";
3117 foreach ( get_post_stati() as $status ) {
3118 if ( in_array( $status, $q_status ) ) {
3119 if ( 'private' == $status )
3120 $p_status[] = "$wpdb->posts.post_status = '$status'";
3122 $r_status[] = "$wpdb->posts.post_status = '$status'";
3127 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
3128 $r_status = array_merge($r_status, $p_status);
3132 if ( !empty($e_status) ) {
3133 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
3135 if ( !empty($r_status) ) {
3136 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
3137 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
3139 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
3141 if ( !empty($p_status) ) {
3142 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
3143 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
3145 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
3147 if ( $post_status_join ) {
3148 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
3149 foreach ( $statuswheres as $index => $statuswhere )
3150 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
3152 $where_status = implode( ' OR ', $statuswheres );
3153 if ( ! empty( $where_status ) ) {
3154 $where .= " AND ($where_status)";
3156 } elseif ( !$this->is_singular ) {
3157 $where .= " AND ($wpdb->posts.post_status = 'publish'";
3159 // Add public states.
3160 $public_states = get_post_stati( array('public' => true) );
3161 foreach ( (array) $public_states as $state ) {
3162 if ( 'publish' == $state ) // Publish is hard-coded above.
3164 $where .= " OR $wpdb->posts.post_status = '$state'";
3167 if ( $this->is_admin ) {
3168 // Add protected states that should show in the admin all list.
3169 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3170 foreach ( (array) $admin_all_states as $state )
3171 $where .= " OR $wpdb->posts.post_status = '$state'";
3174 if ( is_user_logged_in() ) {
3175 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3176 $private_states = get_post_stati( array('private' => true) );
3177 foreach ( (array) $private_states as $state )
3178 $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'";
3185 * Apply filters on where and join prior to paging so that any
3186 * manipulations to them are reflected in the paging by day queries.
3188 if ( !$q['suppress_filters'] ) {
3190 * Filter the WHERE clause of the query.
3194 * @param string $where The WHERE clause of the query.
3195 * @param WP_Query &$this The WP_Query instance (passed by reference).
3197 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3200 * Filter the JOIN clause of the query.
3204 * @param string $where The JOIN clause of the query.
3205 * @param WP_Query &$this The WP_Query instance (passed by reference).
3207 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3211 if ( empty($q['nopaging']) && !$this->is_singular ) {
3212 $page = absint($q['paged']);
3216 // If 'offset' is provided, it takes precedence over 'paged'.
3217 if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
3218 $q['offset'] = absint( $q['offset'] );
3219 $pgstrt = $q['offset'] . ', ';
3221 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3223 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3227 if ( $this->is_comment_feed && ! $this->is_singular ) {
3228 if ( $this->is_archive || $this->is_search ) {
3229 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3230 $cwhere = "WHERE comment_approved = '1' $where";
3231 $cgroupby = "$wpdb->comments.comment_id";
3232 } else { // Other non singular e.g. front
3233 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3234 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
3238 if ( !$q['suppress_filters'] ) {
3240 * Filter the JOIN clause of the comments feed query before sending.
3244 * @param string $cjoin The JOIN clause of the query.
3245 * @param WP_Query &$this The WP_Query instance (passed by reference).
3247 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3250 * Filter the WHERE clause of the comments feed query before sending.
3254 * @param string $cwhere The WHERE clause of the query.
3255 * @param WP_Query &$this The WP_Query instance (passed by reference).
3257 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3260 * Filter the GROUP BY clause of the comments feed query before sending.
3264 * @param string $cgroupby The GROUP BY clause of the query.
3265 * @param WP_Query &$this The WP_Query instance (passed by reference).
3267 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3270 * Filter the ORDER BY clause of the comments feed query before sending.
3274 * @param string $corderby The ORDER BY clause of the query.
3275 * @param WP_Query &$this The WP_Query instance (passed by reference).
3277 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3280 * Filter the LIMIT clause of the comments feed query before sending.
3284 * @param string $climits The JOIN clause of the query.
3285 * @param WP_Query &$this The WP_Query instance (passed by reference).
3287 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3289 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3290 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3292 $comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3293 // Convert to WP_Comment
3294 $this->comments = array_map( 'get_comment', $comments );
3295 $this->comment_count = count($this->comments);
3297 $post_ids = array();
3299 foreach ( $this->comments as $comment )
3300 $post_ids[] = (int) $comment->comment_post_ID;
3302 $post_ids = join(',', $post_ids);
3305 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3310 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3313 * Apply post-paging filters on where and join. Only plugins that
3314 * manipulate paging queries should use these hooks.
3316 if ( !$q['suppress_filters'] ) {
3318 * Filter the WHERE clause of the query.
3320 * Specifically for manipulating paging queries.
3324 * @param string $where The WHERE clause of the query.
3325 * @param WP_Query &$this The WP_Query instance (passed by reference).
3327 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3330 * Filter the GROUP BY clause of the query.
3334 * @param string $groupby The GROUP BY clause of the query.
3335 * @param WP_Query &$this The WP_Query instance (passed by reference).
3337 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3340 * Filter the JOIN clause of the query.
3342 * Specifically for manipulating paging queries.
3346 * @param string $join The JOIN clause of the query.
3347 * @param WP_Query &$this The WP_Query instance (passed by reference).
3349 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3352 * Filter the ORDER BY clause of the query.
3356 * @param string $orderby The ORDER BY clause of the query.
3357 * @param WP_Query &$this The WP_Query instance (passed by reference).
3359 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3362 * Filter the DISTINCT clause of the query.
3366 * @param string $distinct The DISTINCT clause of the query.
3367 * @param WP_Query &$this The WP_Query instance (passed by reference).
3369 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3372 * Filter the LIMIT clause of the query.
3376 * @param string $limits The LIMIT clause of the query.
3377 * @param WP_Query &$this The WP_Query instance (passed by reference).
3379 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3382 * Filter the SELECT clause of the query.