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 = '(CASE ';
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 );
2324 $search_orderby .= 'ELSE 5 END)';
2326 // single word or sentence search
2327 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2330 return $search_orderby;
2334 * If the passed orderby value is allowed, convert the alias to a
2335 * properly-prefixed orderby value.
2340 * @global wpdb $wpdb WordPress database abstraction object.
2342 * @param string $orderby Alias for the field to order by.
2343 * @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
2345 protected function parse_orderby( $orderby ) {
2348 // Used to filter values.
2349 $allowed_keys = array(
2350 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2351 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2352 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2355 $primary_meta_key = '';
2356 $primary_meta_query = false;
2357 $meta_clauses = $this->meta_query->get_clauses();
2358 if ( ! empty( $meta_clauses ) ) {
2359 $primary_meta_query = reset( $meta_clauses );
2361 if ( ! empty( $primary_meta_query['key'] ) ) {
2362 $primary_meta_key = $primary_meta_query['key'];
2363 $allowed_keys[] = $primary_meta_key;
2366 $allowed_keys[] = 'meta_value';
2367 $allowed_keys[] = 'meta_value_num';
2368 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
2371 if ( ! in_array( $orderby, $allowed_keys, true ) ) {
2375 switch ( $orderby ) {
2380 case 'post_modified':
2385 case 'comment_count':
2386 $orderby_clause = "$wpdb->posts.{$orderby}";
2389 $orderby_clause = 'RAND()';
2391 case $primary_meta_key:
2393 if ( ! empty( $primary_meta_query['type'] ) ) {
2394 $orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
2396 $orderby_clause = "{$primary_meta_query['alias']}.meta_value";
2399 case 'meta_value_num':
2400 $orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
2403 if ( array_key_exists( $orderby, $meta_clauses ) ) {
2404 // $orderby corresponds to a meta_query clause.
2405 $meta_clause = $meta_clauses[ $orderby ];
2406 $orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
2408 // Default: order by post field.
2409 $orderby_clause = "$wpdb->posts.post_" . sanitize_key( $orderby );
2415 return $orderby_clause;
2419 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2424 * @param string $order The 'order' query variable.
2425 * @return string The sanitized 'order' query variable.
2427 protected function parse_order( $order ) {
2428 if ( ! is_string( $order ) || empty( $order ) ) {
2432 if ( 'ASC' === strtoupper( $order ) ) {
2440 * Sets the 404 property and saves whether query is feed.
2445 public function set_404() {
2446 $is_feed = $this->is_feed;
2448 $this->init_query_flags();
2449 $this->is_404 = true;
2451 $this->is_feed = $is_feed;
2455 * Retrieve query variable.
2458 * @since 3.9.0 The `$default` argument was introduced.
2462 * @param string $query_var Query variable key.
2463 * @param mixed $default Optional. Value to return if the query variable is not set. Default empty.
2464 * @return mixed Contents of the query variable.
2466 public function get( $query_var, $default = '' ) {
2467 if ( isset( $this->query_vars[ $query_var ] ) ) {
2468 return $this->query_vars[ $query_var ];
2475 * Set query variable.
2480 * @param string $query_var Query variable key.
2481 * @param mixed $value Query variable value.
2483 public function set($query_var, $value) {
2484 $this->query_vars[$query_var] = $value;
2488 * Retrieve the posts based on query variables.
2490 * There are a few filters and actions that can be used to modify the post
2496 * @global wpdb $wpdb WordPress database abstraction object.
2498 * @return array List of posts.
2500 public function get_posts() {
2503 $this->parse_query();
2506 * Fires after the query variable object is created, but before the actual query is run.
2508 * Note: If using conditional tags, use the method versions within the passed instance
2509 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2510 * like is_main_query() test against the global $wp_query instance, not the passed one.
2514 * @param WP_Query &$this The WP_Query instance (passed by reference).
2516 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2519 $q = &$this->query_vars;
2521 // Fill again in case pre_get_posts unset some vars.
2522 $q = $this->fill_query_vars($q);
2525 $this->meta_query = new WP_Meta_Query();
2526 $this->meta_query->parse_query_vars( $q );
2528 // Set a flag if a pre_get_posts hook changed the query vars.
2529 $hash = md5( serialize( $this->query_vars ) );
2530 if ( $hash != $this->query_vars_hash ) {
2531 $this->query_vars_changed = true;
2532 $this->query_vars_hash = $hash;
2536 // First let's clear some variables
2539 $whichmimetype = '';
2545 $post_status_join = false;
2548 if ( isset( $q['caller_get_posts'] ) ) {
2549 _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2550 if ( !isset( $q['ignore_sticky_posts'] ) )
2551 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2554 if ( !isset( $q['ignore_sticky_posts'] ) )
2555 $q['ignore_sticky_posts'] = false;
2557 if ( !isset($q['suppress_filters']) )
2558 $q['suppress_filters'] = false;
2560 if ( !isset($q['cache_results']) ) {
2561 if ( wp_using_ext_object_cache() )
2562 $q['cache_results'] = false;
2564 $q['cache_results'] = true;
2567 if ( !isset($q['update_post_term_cache']) )
2568 $q['update_post_term_cache'] = true;
2570 if ( !isset($q['update_post_meta_cache']) )
2571 $q['update_post_meta_cache'] = true;
2573 if ( !isset($q['post_type']) ) {
2574 if ( $this->is_search )
2575 $q['post_type'] = 'any';
2577 $q['post_type'] = '';
2579 $post_type = $q['post_type'];
2580 if ( empty( $q['posts_per_page'] ) ) {
2581 $q['posts_per_page'] = get_option( 'posts_per_page' );
2583 if ( isset($q['showposts']) && $q['showposts'] ) {
2584 $q['showposts'] = (int) $q['showposts'];
2585 $q['posts_per_page'] = $q['showposts'];
2587 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2588 $q['posts_per_page'] = $q['posts_per_archive_page'];
2589 if ( !isset($q['nopaging']) ) {
2590 if ( $q['posts_per_page'] == -1 ) {
2591 $q['nopaging'] = true;
2593 $q['nopaging'] = false;
2597 if ( $this->is_feed ) {
2598 // This overrides posts_per_page.
2599 if ( ! empty( $q['posts_per_rss'] ) ) {
2600 $q['posts_per_page'] = $q['posts_per_rss'];
2602 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2604 $q['nopaging'] = false;
2606 $q['posts_per_page'] = (int) $q['posts_per_page'];
2607 if ( $q['posts_per_page'] < -1 )
2608 $q['posts_per_page'] = abs($q['posts_per_page']);
2609 elseif ( $q['posts_per_page'] == 0 )
2610 $q['posts_per_page'] = 1;
2612 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2613 $q['comments_per_page'] = get_option('comments_per_page');
2615 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2616 $this->is_page = true;
2617 $this->is_home = false;
2618 $q['page_id'] = get_option('page_on_front');
2621 if ( isset($q['page']) ) {
2622 $q['page'] = trim($q['page'], '/');
2623 $q['page'] = absint($q['page']);
2626 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2627 if ( isset($q['no_found_rows']) )
2628 $q['no_found_rows'] = (bool) $q['no_found_rows'];
2630 $q['no_found_rows'] = false;
2632 switch ( $q['fields'] ) {
2634 $fields = "$wpdb->posts.ID";
2637 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2640 $fields = "$wpdb->posts.*";
2643 if ( '' !== $q['menu_order'] )
2644 $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2646 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2648 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2649 if ( strlen($q['m']) > 5 )
2650 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2651 if ( strlen($q['m']) > 7 )
2652 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2653 if ( strlen($q['m']) > 9 )
2654 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2655 if ( strlen($q['m']) > 11 )
2656 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2657 if ( strlen($q['m']) > 13 )
2658 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2661 // Handle the other individual date parameters
2662 $date_parameters = array();
2664 if ( '' !== $q['hour'] )
2665 $date_parameters['hour'] = $q['hour'];
2667 if ( '' !== $q['minute'] )
2668 $date_parameters['minute'] = $q['minute'];
2670 if ( '' !== $q['second'] )
2671 $date_parameters['second'] = $q['second'];
2674 $date_parameters['year'] = $q['year'];
2676 if ( $q['monthnum'] )
2677 $date_parameters['monthnum'] = $q['monthnum'];
2680 $date_parameters['week'] = $q['w'];
2683 $date_parameters['day'] = $q['day'];
2685 if ( $date_parameters ) {
2686 $date_query = new WP_Date_Query( array( $date_parameters ) );
2687 $where .= $date_query->get_sql();
2689 unset( $date_parameters, $date_query );
2691 // Handle complex date queries
2692 if ( ! empty( $q['date_query'] ) ) {
2693 $this->date_query = new WP_Date_Query( $q['date_query'] );
2694 $where .= $this->date_query->get_sql();
2698 // If we've got a post_type AND it's not "any" post_type.
2699 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2700 foreach ( (array)$q['post_type'] as $_post_type ) {
2701 $ptype_obj = get_post_type_object($_post_type);
2702 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2705 if ( ! $ptype_obj->hierarchical ) {
2706 // Non-hierarchical post types can directly use 'name'.
2707 $q['name'] = $q[ $ptype_obj->query_var ];
2709 // Hierarchical post types will operate through 'pagename'.
2710 $q['pagename'] = $q[ $ptype_obj->query_var ];
2714 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2720 if ( '' !== $q['title'] ) {
2721 $where .= $wpdb->prepare( " AND $wpdb->posts.post_title = %s", stripslashes( $q['title'] ) );
2724 // Parameters related to 'post_name'.
2725 if ( '' != $q['name'] ) {
2726 $q['name'] = sanitize_title_for_query( $q['name'] );
2727 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2728 } elseif ( '' != $q['pagename'] ) {
2729 if ( isset($this->queried_object_id) ) {
2730 $reqpage = $this->queried_object_id;
2732 if ( 'page' != $q['post_type'] ) {
2733 foreach ( (array)$q['post_type'] as $_post_type ) {
2734 $ptype_obj = get_post_type_object($_post_type);
2735 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2738 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2744 $reqpage = get_page_by_path($q['pagename']);
2746 if ( !empty($reqpage) )
2747 $reqpage = $reqpage->ID;
2752 $page_for_posts = get_option('page_for_posts');
2753 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2754 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2755 $q['name'] = $q['pagename'];
2756 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2757 $reqpage_obj = get_post( $reqpage );
2758 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2759 $this->is_attachment = true;
2760 $post_type = $q['post_type'] = 'attachment';
2761 $this->is_page = true;
2762 $q['attachment_id'] = $reqpage;
2765 } elseif ( '' != $q['attachment'] ) {
2766 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2767 $q['name'] = $q['attachment'];
2768 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2769 } elseif ( is_array( $q['post_name__in'] ) && ! empty( $q['post_name__in'] ) ) {
2770 $q['post_name__in'] = array_map( 'sanitize_title_for_query', $q['post_name__in'] );
2771 $where .= " AND $wpdb->posts.post_name IN ('" . implode( "' ,'", $q['post_name__in'] ) . "')";
2774 if ( intval($q['comments_popup']) )
2775 $q['p'] = absint($q['comments_popup']);
2777 // If an attachment is requested by number, let it supersede any post number.
2778 if ( $q['attachment_id'] )
2779 $q['p'] = absint($q['attachment_id']);
2781 // If a post number is specified, load that post
2783 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2784 } elseif ( $q['post__in'] ) {
2785 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2786 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2787 } elseif ( $q['post__not_in'] ) {
2788 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
2789 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2792 if ( is_numeric( $q['post_parent'] ) ) {
2793 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2794 } elseif ( $q['post_parent__in'] ) {
2795 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2796 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2797 } elseif ( $q['post_parent__not_in'] ) {
2798 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
2799 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2802 if ( $q['page_id'] ) {
2803 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2804 $q['p'] = $q['page_id'];
2805 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2809 // If a search pattern is specified, load the posts that match.
2810 if ( ! empty( $q['s'] ) ) {
2811 $search = $this->parse_search( $q );
2815 * Filter the search SQL that is used in the WHERE clause of WP_Query.
2819 * @param string $search Search SQL for WHERE clause.
2820 * @param WP_Query $this The current WP_Query object.
2822 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2825 if ( !$this->is_singular ) {
2826 $this->parse_tax_query( $q );
2828 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2830 $join .= $clauses['join'];
2831 $where .= $clauses['where'];
2834 if ( $this->is_tax ) {
2835 if ( empty($post_type) ) {
2836 // Do a fully inclusive search for currently registered post types of queried taxonomies
2837 $post_type = array();
2838 $taxonomies = array_keys( $this->tax_query->queried_terms );
2839 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2840 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2841 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2846 elseif ( count( $post_type ) == 1 )
2847 $post_type = $post_type[0];
2849 $post_status_join = true;
2850 } elseif ( in_array('attachment', (array) $post_type) ) {
2851 $post_status_join = true;
2856 * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2857 * 'category_name' vars are set for backward compatibility.
2859 if ( ! empty( $this->tax_query->queried_terms ) ) {
2862 * Set 'taxonomy', 'term', and 'term_id' to the
2863 * first taxonomy other than 'post_tag' or 'category'.
2865 if ( ! isset( $q['taxonomy'] ) ) {
2866 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2867 if ( empty( $queried_items['terms'][0] ) ) {
2871 if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2872 $q['taxonomy'] = $queried_taxonomy;
2874 if ( 'slug' === $queried_items['field'] ) {
2875 $q['term'] = $queried_items['terms'][0];
2877 $q['term_id'] = $queried_items['terms'][0];
2883 // 'cat', 'category_name', 'tag_id'
2884 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2885 if ( empty( $queried_items['terms'][0] ) ) {
2889 if ( 'category' === $queried_taxonomy ) {
2890 $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2892 $this->set( 'cat', $the_cat->term_id );
2893 $this->set( 'category_name', $the_cat->slug );
2898 if ( 'post_tag' === $queried_taxonomy ) {
2899 $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2901 $this->set( 'tag_id', $the_tag->term_id );
2908 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2909 $groupby = "{$wpdb->posts}.ID";
2912 // Author/user stuff
2914 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2915 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2916 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2917 foreach ( $authors as $author ) {
2918 $key = $author > 0 ? 'author__in' : 'author__not_in';
2919 $q[$key][] = abs( $author );
2921 $q['author'] = implode( ',', $authors );
2924 if ( ! empty( $q['author__not_in'] ) ) {
2925 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2926 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2927 } elseif ( ! empty( $q['author__in'] ) ) {
2928 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2929 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2932 // Author stuff for nice URLs
2934 if ( '' != $q['author_name'] ) {
2935 if ( strpos($q['author_name'], '/') !== false ) {
2936 $q['author_name'] = explode('/', $q['author_name']);
2937 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2938 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2940 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2943 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2944 $q['author'] = get_user_by('slug', $q['author_name']);
2946 $q['author'] = $q['author']->ID;
2947 $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2950 // MIME-Type stuff for attachment browsing
2952 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2953 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2955 $where .= $search . $whichauthor . $whichmimetype;
2957 if ( ! empty( $this->meta_query->queries ) ) {
2958 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
2959 $join .= $clauses['join'];
2960 $where .= $clauses['where'];
2963 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2964 if ( ! isset( $q['order'] ) ) {
2965 $q['order'] = $rand ? '' : 'DESC';
2967 $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2971 if ( empty( $q['orderby'] ) ) {
2973 * Boolean false or empty array blanks out ORDER BY,
2974 * while leaving the value unset or otherwise empty sets the default.
2976 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2979 $orderby = "$wpdb->posts.post_date " . $q['order'];
2981 } elseif ( 'none' == $q['orderby'] ) {
2983 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2984 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2985 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2986 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2988 $orderby_array = array();
2989 if ( is_array( $q['orderby'] ) ) {
2990 foreach ( $q['orderby'] as $_orderby => $order ) {
2991 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2992 $parsed = $this->parse_orderby( $orderby );
2998 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
3000 $orderby = implode( ', ', $orderby_array );
3003 $q['orderby'] = urldecode( $q['orderby'] );
3004 $q['orderby'] = addslashes_gpc( $q['orderby'] );
3006 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
3007 $parsed = $this->parse_orderby( $orderby );
3008 // Only allow certain values for safety.
3013 $orderby_array[] = $parsed;
3015 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
3017 if ( empty( $orderby ) ) {
3018 $orderby = "$wpdb->posts.post_date " . $q['order'];
3019 } elseif ( ! empty( $q['order'] ) ) {
3020 $orderby .= " {$q['order']}";
3025 // Order search results by relevance only when another "orderby" is not specified in the query.
3026 if ( ! empty( $q['s'] ) ) {
3027 $search_orderby = '';
3028 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
3029 $search_orderby = $this->parse_search_order( $q );
3032 * Filter the ORDER BY used when ordering search results.
3036 * @param string $search_orderby The ORDER BY clause.
3037 * @param WP_Query $this The current WP_Query instance.
3039 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
3040 if ( $search_orderby )
3041 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
3044 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
3045 $post_type_cap = 'multiple_post_type';
3047 if ( is_array( $post_type ) )
3048 $post_type = reset( $post_type );
3049 $post_type_object = get_post_type_object( $post_type );
3050 if ( empty( $post_type_object ) )
3051 $post_type_cap = $post_type;
3054 if ( isset( $q['post_password'] ) ) {
3055 $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
3056 if ( empty( $q['perm'] ) ) {
3057 $q['perm'] = 'readable';
3059 } elseif ( isset( $q['has_password'] ) ) {
3060 $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
3063 if ( 'any' == $post_type ) {
3064 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
3065 if ( empty( $in_search_post_types ) )
3066 $where .= ' AND 1=0 ';
3068 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')";
3069 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
3070 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
3071 } elseif ( ! empty( $post_type ) ) {
3072 $where .= " AND $wpdb->posts.post_type = '$post_type'";
3073 $post_type_object = get_post_type_object ( $post_type );
3074 } elseif ( $this->is_attachment ) {
3075 $where .= " AND $wpdb->posts.post_type = 'attachment'";
3076 $post_type_object = get_post_type_object ( 'attachment' );
3077 } elseif ( $this->is_page ) {
3078 $where .= " AND $wpdb->posts.post_type = 'page'";
3079 $post_type_object = get_post_type_object ( 'page' );
3081 $where .= " AND $wpdb->posts.post_type = 'post'";
3082 $post_type_object = get_post_type_object ( 'post' );
3085 $edit_cap = 'edit_post';
3086 $read_cap = 'read_post';
3088 if ( ! empty( $post_type_object ) ) {
3089 $edit_others_cap = $post_type_object->cap->edit_others_posts;
3090 $read_private_cap = $post_type_object->cap->read_private_posts;
3092 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
3093 $read_private_cap = 'read_private_' . $post_type_cap . 's';
3096 $user_id = get_current_user_id();
3098 $q_status = array();
3099 if ( ! empty( $q['post_status'] ) ) {
3100 $statuswheres = array();
3101 $q_status = $q['post_status'];
3102 if ( ! is_array( $q_status ) )
3103 $q_status = explode(',', $q_status);
3104 $r_status = array();
3105 $p_status = array();
3106 $e_status = array();
3107 if ( in_array( 'any', $q_status ) ) {
3108 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
3109 if ( ! in_array( $status, $q_status ) ) {
3110 $e_status[] = "$wpdb->posts.post_status <> '$status'";
3114 foreach ( get_post_stati() as $status ) {
3115 if ( in_array( $status, $q_status ) ) {
3116 if ( 'private' == $status )
3117 $p_status[] = "$wpdb->posts.post_status = '$status'";
3119 $r_status[] = "$wpdb->posts.post_status = '$status'";
3124 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
3125 $r_status = array_merge($r_status, $p_status);
3129 if ( !empty($e_status) ) {
3130 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
3132 if ( !empty($r_status) ) {
3133 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
3134 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
3136 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
3138 if ( !empty($p_status) ) {
3139 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
3140 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
3142 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
3144 if ( $post_status_join ) {
3145 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
3146 foreach ( $statuswheres as $index => $statuswhere )
3147 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
3149 $where_status = implode( ' OR ', $statuswheres );
3150 if ( ! empty( $where_status ) ) {
3151 $where .= " AND ($where_status)";
3153 } elseif ( !$this->is_singular ) {
3154 $where .= " AND ($wpdb->posts.post_status = 'publish'";
3156 // Add public states.
3157 $public_states = get_post_stati( array('public' => true) );
3158 foreach ( (array) $public_states as $state ) {
3159 if ( 'publish' == $state ) // Publish is hard-coded above.
3161 $where .= " OR $wpdb->posts.post_status = '$state'";
3164 if ( $this->is_admin ) {
3165 // Add protected states that should show in the admin all list.
3166 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3167 foreach ( (array) $admin_all_states as $state )
3168 $where .= " OR $wpdb->posts.post_status = '$state'";
3171 if ( is_user_logged_in() ) {
3172 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3173 $private_states = get_post_stati( array('private' => true) );
3174 foreach ( (array) $private_states as $state )
3175 $where .= current_user_can( $read_private_cap ) ? " OR $wpdb->posts.post_status = '$state'" : " OR $wpdb->posts.post_author = $user_id AND $wpdb->posts.post_status = '$state'";
3182 * Apply filters on where and join prior to paging so that any
3183 * manipulations to them are reflected in the paging by day queries.
3185 if ( !$q['suppress_filters'] ) {
3187 * Filter the WHERE clause of the query.
3191 * @param string $where The WHERE clause of the query.
3192 * @param WP_Query &$this The WP_Query instance (passed by reference).
3194 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3197 * Filter the JOIN clause of the query.
3201 * @param string $where The JOIN clause of the query.
3202 * @param WP_Query &$this The WP_Query instance (passed by reference).
3204 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3208 if ( empty($q['nopaging']) && !$this->is_singular ) {
3209 $page = absint($q['paged']);
3213 // If 'offset' is provided, it takes precedence over 'paged'.
3214 if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
3215 $q['offset'] = absint( $q['offset'] );
3216 $pgstrt = $q['offset'] . ', ';
3218 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3220 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3224 if ( $this->is_comment_feed && ! $this->is_singular ) {
3225 if ( $this->is_archive || $this->is_search ) {
3226 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3227 $cwhere = "WHERE comment_approved = '1' $where";
3228 $cgroupby = "$wpdb->comments.comment_id";
3229 } else { // Other non singular e.g. front
3230 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3231 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
3235 if ( !$q['suppress_filters'] ) {
3237 * Filter the JOIN clause of the comments feed query before sending.
3241 * @param string $cjoin The JOIN clause of the query.
3242 * @param WP_Query &$this The WP_Query instance (passed by reference).
3244 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3247 * Filter the WHERE clause of the comments feed query before sending.
3251 * @param string $cwhere The WHERE clause of the query.
3252 * @param WP_Query &$this The WP_Query instance (passed by reference).
3254 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3257 * Filter the GROUP BY clause of the comments feed query before sending.
3261 * @param string $cgroupby The GROUP BY clause of the query.
3262 * @param WP_Query &$this The WP_Query instance (passed by reference).
3264 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3267 * Filter the ORDER BY clause of the comments feed query before sending.
3271 * @param string $corderby The ORDER BY clause of the query.
3272 * @param WP_Query &$this The WP_Query instance (passed by reference).
3274 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3277 * Filter the LIMIT clause of the comments feed query before sending.
3281 * @param string $climits The JOIN clause of the query.
3282 * @param WP_Query &$this The WP_Query instance (passed by reference).
3284 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3286 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3287 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3289 $comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3290 // Convert to WP_Comment
3291 $this->comments = array_map( 'get_comment', $comments );
3292 $this->comment_count = count($this->comments);
3294 $post_ids = array();
3296 foreach ( $this->comments as $comment )
3297 $post_ids[] = (int) $comment->comment_post_ID;
3299 $post_ids = join(',', $post_ids);
3302 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3307 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3310 * Apply post-paging filters on where and join. Only plugins that
3311 * manipulate paging queries should use these hooks.
3313 if ( !$q['suppress_filters'] ) {
3315 * Filter the WHERE clause of the query.
3317 * Specifically for manipulating paging queries.
3321 * @param string $where The WHERE clause of the query.
3322 * @param WP_Query &$this The WP_Query instance (passed by reference).
3324 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3327 * Filter the GROUP BY clause of the query.
3331 * @param string $groupby The GROUP BY clause of the query.
3332 * @param WP_Query &$this The WP_Query instance (passed by reference).
3334 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3337 * Filter the JOIN clause of the query.
3339 * Specifically for manipulating paging queries.
3343 * @param string $join The JOIN clause of the query.
3344 * @param WP_Query &$this The WP_Query instance (passed by reference).
3346 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3349 * Filter the ORDER BY clause of the query.
3353 * @param string $orderby The ORDER BY clause of the query.
3354 * @param WP_Query &$this The WP_Query instance (passed by reference).
3356 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3359 * Filter the DISTINCT clause of the query.
3363 * @param string $distinct The DISTINCT clause of the query.
3364 * @param WP_Query &$this The WP_Query instance (passed by reference).
3366 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3369 * Filter the LIMIT clause of the query.
3373 * @param string $limits The LIMIT clause of the query.
3374 * @param WP_Query &$this The WP_Query instance (passed by reference).
3376 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3379 * Filter the SELECT clause of the query.
3383 * @param string $fields The SELECT clause of the query.
3384 * @param WP_Query &$this The WP_Query instance (passed by reference).
3386 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3389 * Filter all query clauses at once, for convenience.
3391 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3392 * fields (SELECT), and LIMITS clauses.
3396 * @param array $clauses The list of clauses for the query.
3397 * @param WP_Query &$this The WP_Query instance (passed by reference).
3399 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3401 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3402 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3403 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3404 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3405 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3406 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3407 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3411 * Fires to announce the query's current selection parameters.
3413 * For use by caching plugins.
3417 * @param string $selection The assembled selection query.
3419 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3422 * Filter again for the benefit of caching plugins.
3423 * Regular plugins should use the hooks above.
3425 if ( !$q['suppress_filters'] ) {
3427 * Filter the WHERE clause of the query.
3429 * For use by caching plugins.
3433 * @param string $where The WHERE clause of the query.
3434 * @param WP_Query &$this The WP_Query instance (passed by reference).
3436 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3439 * Filter the GROUP BY clause of the query.
3441 * For use by caching plugins.
3445 * @param string $groupby The GROUP BY clause of the query.
3446 * @param WP_Query &$this The WP_Query instance (passed by reference).
3448 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3451 * Filter the JOIN clause of the query.
3453 * For use by caching plugins.
3457 * @param string $join The JOIN clause of the query.
3458 * @param WP_Query &$this The WP_Query instance (passed by reference).
3460 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3463 * Filter the ORDER BY clause of the query.
3465 * For use by caching plugins.
3469 * @param string $orderby The ORDER BY clause of the query.
3470 * @param WP_Query &$this The WP_Query instance (passed by reference).
3472 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3475 * Filter the DISTINCT clause of the query.
3477 * For use by caching plugins.
3481 * @param string $distinct The DISTINCT clause of the query.
3482 * @param WP_Query &$this The WP_Query instance (passed by reference).
3484 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3487 * Filter the SELECT clause of the query.
3489 * For use by caching plugins.
3493 * @param string $fields The SELECT clause of the query.
3494 * @param WP_Query &$this The WP_Query instance (passed by reference).
3496 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3499 * Filter the LIMIT clause of the query.
3501 * For use by caching plugins.
3505 * @param string $limits The LIMIT clause of the query.
3506 * @param WP_Query &$this The WP_Query instance (passed by reference).
3508 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3511 * Filter all query clauses at once, for convenience.
3513 * For use by caching plugins.
3515 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3516 * fields (SELECT), and LIMITS clauses.
3520 * @param array $pieces The pieces of the query.
3521 * @param WP_Query &$this The WP_Query instance (passed by reference).
3523 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3525 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3526 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3527 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3528 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3529 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3530 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3531 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3534 if ( ! empty($groupby) )
3535 $groupby = 'GROUP BY ' . $groupby;
3536 if ( !empty( $orderby ) )
3537 $orderby = 'ORDER BY ' . $orderby;
3540 if ( !$q['no_found_rows'] && !empty($limits) )
3541 $found_rows = 'SQL_CALC_FOUND_ROWS';
3543 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3545 if ( !$q['suppress_filters'] ) {
3547 * Filter the completed SQL query before sending.
3551 * @param array $request The complete SQL query.
3552 * @param WP_Query &$this The WP_Query instance (passed by reference).
3554 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3557 if ( 'ids' == $q['fields'] ) {
3558 $this->posts = $wpdb->get_col( $this->request );
3559 $this->posts = array_map( 'intval', $this->posts );
3560 $this->post_count = count( $this->posts );
3561 $this->set_found_posts( $q, $limits );
3563 return $this->posts;
3566 if ( 'id=>parent' == $q['fields'] ) {
3567 $this->posts = $wpdb->get_results( $this->request );
3568 $this->post_count = count( $this->posts );
3569 $this->set_found_posts( $q, $limits );
3572 foreach ( $this->posts as $key => $post ) {
3573 $this->posts[ $key ]->ID = (int) $post->ID;
3574 $this->posts[ $key ]->post_parent = (int) $post->post_parent;
3576 $r[ (int) $post->ID ] = (int) $post->post_parent;
3582 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3585 * Filter whether to split the query.
3587 * Splitting the query will cause it to fetch just the IDs of the found posts
3588 * (and then individually fetch each post by ID), rather than fetching every
3589 * complete row at once. One massive result vs. many small results.
3593 * @param bool $split_the_query Whether or not to split the query.
3594 * @param WP_Query $this The WP_Query instance.
3596 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3598 if ( $split_the_query ) {
3599 // First get the IDs and then fill in the objects
3601 $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3604 * Filter the Post IDs SQL request before sending.
3608 * @param string $request The post ID request.
3609 * @param WP_Query $this The WP_Query instance.
3611 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3613 $ids = $wpdb->get_col( $this->request );
3616 $this->posts = $ids;
3617 $this->set_found_posts( $q, $limits );
3618 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3620 $this->posts = array();
3623 $this->posts = $wpdb->get_results( $this->request );
3624 $this->set_found_posts( $q, $limits );
3627 // Convert to WP_Post objects
3629 $this->posts = array_map( 'get_post', $this->posts );
3632 if ( $q['update_post_term_cache'] ) {
3633 add_filter( 'get_term_metadata', array( $this, 'lazyload_term_meta' ), 10, 2 );
3636 if ( ! $q['suppress_filters'] ) {
3638 * Filter the raw post results array, prior to status checks.
3642 * @param array $posts The post results array.
3643 * @param WP_Query &$this The WP_Query instance (passed by reference).
3645 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3648 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3649 /** This filter is documented in wp-includes/query.php */
3650 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3652 /** This filter is documented in wp-includes/query.php */
3653 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3655 /** This filter is documented in wp-includes/query.php */
3656 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3657 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3659 /** This filter is documented in wp-includes/query.php */
3660 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3661 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3663 /** This filter is documented in wp-includes/query.php */
3664 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3666 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3667 $comments = $wpdb->get_results($comments_request);
3668 // Convert to WP_Comment
3669 $this->comments = array_map( 'get_comment', $comments );
3670 $this->comment_count = count($this->comments);
3673 // Check post status to determine if post should be displayed.
3674 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3675 $status = get_post_status($this->posts[0]);
3676 if ( 'attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent ) {
3677 $this->is_page = false;
3678 $this->is_single = true;
3679 $this->is_attachment = true;
3681 $post_status_obj = get_post_status_object($status);
3682 //$type = get_post_type($this->posts[0]);
3684 // If the post_status was specifically requested, let it pass through.
3685 if ( !$post_status_obj->public && ! in_array( $status, $q_status ) ) {
3687 if ( ! is_user_logged_in() ) {
3688 // User must be logged in to view unpublished posts.
3689 $this->posts = array();
3691 if ( $post_status_obj->protected ) {
3692 // User must have edit permissions on the draft to preview.
3693 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3694 $this->posts = array();
3696 $this->is_preview = true;
3697 if ( 'future' != $status )
3698 $this->posts[0]->post_date = current_time('mysql');
3700 } elseif ( $post_status_obj->private ) {
3701 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3702 $this->posts = array();
3704 $this->posts = array();
3709 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3711 * Filter the single post for preview mode.
3715 * @param WP_Post $post_preview The Post object.
3716 * @param WP_Query &$this The WP_Query instance (passed by reference).
3718 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3722 // Put sticky posts at the top of the posts array
3723 $sticky_posts = get_option('sticky_posts');
3724 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3725 $num_posts = count($this->posts);
3727 // Loop over posts and relocate stickies to the front.
3728 for ( $i = 0; $i < $num_posts; $i++ ) {
3729 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3730 $sticky_post = $this->posts[$i];
3731 // Remove sticky from current position
3732 array_splice($this->posts, $i, 1);
3733 // Move to front, after other stickies
3734 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3735 // Increment the sticky offset. The next sticky will be placed at this offset.
3737 // Remove post from sticky posts array
3738 $offset = array_search($sticky_post->ID, $sticky_posts);
3739 unset( $sticky_posts[$offset] );
3743 // If any posts have been excluded specifically, Ignore those that are sticky.
3744 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3745 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3747 // Fetch sticky posts that weren't in the query results
3748 if ( !empty($sticky_posts) ) {
3749 $stickies = get_posts( array(
3750 'post__in' => $sticky_posts,
3751 'post_type' => $post_type,
3752 'post_status' => 'publish',
3756 foreach ( $stickies as $sticky_post ) {
3757 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3763 // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
3764 if ( ! empty( $this->comments ) ) {
3765 add_filter( 'get_comment_metadata', array( $this, 'lazyload_comment_meta' ), 10, 2 );
3768 if ( ! $q['suppress_filters'] ) {
3770 * Filter the array of retrieved posts after they've been fetched and
3771 * internally processed.
3775 * @param array $posts The array of retrieved posts.
3776 * @param WP_Query &$this The WP_Query instance (passed by reference).
3778 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3781 // Ensure that any posts added/modified via one of the filters above are
3782 // of the type WP_Post and are filtered.
3783 if ( $this->posts ) {
3784 $this->post_count = count( $this->posts );
3786 $this->posts = array_map( 'get_post', $this->posts );
3788 if ( $q['cache_results'] )
3789 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3791 $this->post = reset( $this->posts );
3793 $this->post_count = 0;
3794 $this->posts = array();
3797 return $this->posts;
3801 * Set up the amount of found posts and the number of pages (if limit clause was used)
3802 * for the current query.
3807 * @global wpdb $wpdb WordPress database abstraction object.
3809 private function set_found_posts( $q, $limits ) {
3812 // Bail if posts is an empty array. Continue if posts is an empty string,
3813 // null, or false to accommodate caching plugins that fill posts later.
3814 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3817 if ( ! empty( $limits ) ) {
3819 * Filter the query to run for retrieving the found posts.
3823 * @param string $found_posts The query to run to find the found posts.
3824 * @param WP_Query &$this The WP_Query instance (passed by reference).
3826 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3828 $this->found_posts = count( $this->posts );
3832 * Filter the number of found posts for the query.
3836 * @param int $found_posts The number of posts found.
3837 * @param WP_Query &$this The WP_Query instance (passed by reference).
3839 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3841 if ( ! empty( $limits ) )
3842 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3846 * Set up the next post and iterate current post index.
3851 * @return WP_Post Next post.
3853 public function next_post() {
3855 $this->current_post++;
3857 $this->post = $this->posts[$this->current_post];
3862 * Sets up the current post.
3864 * Retrieves the next post, sets up the post, sets the 'in the loop'
3870 * @global WP_Post $post
3872 public function the_post() {
3874 $this->in_the_loop = true;
3876 if ( $this->current_post == -1 ) // loop has just started
3878 * Fires once the loop is started.
3882 * @param WP_Query &$this The WP_Query instance (passed by reference).
3884 do_action_ref_array( 'loop_start', array( &$this ) );
3886 $post = $this->next_post();
3887 $this->setup_postdata( $post );
3891 * Whether there are more posts available in the loop.
3893 * Calls action 'loop_end', when the loop is complete.
3898 * @return bool True if posts are available, false if end of loop.
3900 public function have_posts() {
3901 if ( $this->current_post + 1 < $this->post_count ) {
3903 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3905 * Fires once the loop has ended.
3909 * @param WP_Query &$this The WP_Query instance (passed by reference).
3911 do_action_ref_array( 'loop_end', array( &$this ) );
3912 // Do some cleaning up after the loop
3913 $this->rewind_posts();
3916 $this->in_the_loop = false;
3921 * Rewind the posts and reset post index.
3926 public function rewind_posts() {
3927 $this->current_post = -1;
3928 if ( $this->post_count > 0 ) {
3929 $this->post = $this->posts[0];
3934 * Iterate current comment index and return WP_Comment object.
3939 * @return WP_Comment Comment object.
3941 public function next_comment() {
3942 $this->current_comment++;
3944 $this->comment = $this->comments[$this->current_comment];
3945 return $this->comment;
3949 * Sets up the current comment.
3953 * @global WP_Comment $comment Current comment.
3955 public function the_comment() {
3958 $comment = $this->next_comment();
3960 if ( $this->current_comment == 0 ) {
3962 * Fires once the comment loop is started.
3966 do_action( 'comment_loop_start' );
3971 * Whether there are more comments available.
3973 * Automatically rewinds comments when finished.
3978 * @return bool True, if more comments. False, if no more posts.
3980 public function have_comments() {
3981 if ( $this->current_comment + 1 < $this->comment_count ) {
3983 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
3984 $this->rewind_comments();
3991 * Rewind the comments, resets the comment index and comment to first.
3996 public function rewind_comments() {
3997 $this->current_comment = -1;
3998 if ( $this->comment_count > 0 ) {
3999 $this->comment = $this->comments[0];
4004 * Sets up the WordPress query by parsing query string.
4009 * @param string $query URL query string.
4010 * @return array List of posts.
4012 public function query( $query ) {
4014 $this->query = $this->query_vars = wp_parse_args( $query );
4015 return $this->get_posts();
4019 * Retrieve queried object.
4021 * If queried object is not set, then the queried object will be set from
4022 * the category, tag, taxonomy, posts page, single post, page, or author
4023 * query variable. After it is set up, it will be returned.
4030 public function get_queried_object() {
4031 if ( isset($this->queried_object) )
4032 return $this->queried_object;
4034 $this->queried_object = null;
4035 $this->queried_object_id = null;
4037 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
4038 if ( $this->is_category ) {
4039 if ( $this->get( 'cat' ) ) {
4040 $term = get_term( $this->get( 'cat' ), 'category' );
4041 } elseif ( $this->get( 'category_name' ) ) {
4042 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
4044 } elseif ( $this->is_tag ) {
4045 if ( $this->get( 'tag_id' ) ) {
4046 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
4047 } elseif ( $this->get( 'tag' ) ) {
4048 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
4051 // For other tax queries, grab the first term from the first clause.
4052 $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' );
4054 if ( ! empty( $tax_query_in_and ) ) {
4055 $queried_taxonomies = array_keys( $tax_query_in_and );
4056 $matched_taxonomy = reset( $queried_taxonomies );
4057 $query = $tax_query_in_and[ $matched_taxonomy ];
4059 if ( $query['terms'] ) {
4060 if ( 'term_id' == $query['field'] ) {
4061 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
4063 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
4069 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
4070 $this->queried_object = $term;
4071 $this->queried_object_id = (int) $term->term_id;
4073 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
4074 _make_cat_compat( $this->queried_object );
4076 } elseif ( $this->is_post_type_archive ) {
4077 $post_type = $this->get( 'post_type' );
4078 if ( is_array( $post_type ) )
4079 $post_type = reset( $post_type );
4080 $this->queried_object = get_post_type_object( $post_type );
4081 } elseif ( $this->is_posts_page ) {
4082 $page_for_posts = get_option('page_for_posts');
4083 $this->queried_object = get_post( $page_for_posts );
4084 $this->queried_object_id = (int) $this->queried_object->ID;
4085 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
4086 $this->queried_object = $this->post;
4087 $this->queried_object_id = (int) $this->post->ID;
4088 } elseif ( $this->is_author ) {
4089 $this->queried_object_id = (int) $this->get('author');
4090 $this->queried_object = get_userdata( $this->queried_object_id );
4093 return $this->queried_object;
4097 * Retrieve ID of the current queried object.
4104 public function get_queried_object_id() {
4105 $this->get_queried_object();
4107 if ( isset($this->queried_object_id) ) {
4108 return $this->queried_object_id;
4117 * Sets up the WordPress query, if parameter is not empty.
4122 * @param string|array $query URL query string or array of vars.
4124 public function __construct($query = '') {
4125 if ( ! empty($query) ) {
4126 $this->query($query);
4131 * Make private properties readable for backwards compatibility.
4136 * @param string $name Property to get.
4137 * @return mixed Property.
4139 public function __get( $name ) {
4140 if ( in_array( $name, $this->compat_fields ) ) {
4141 return $this->$name;
4146 * Make private properties checkable for backwards compatibility.
4151 * @param string $name Property to check if set.
4152 * @return bool Whether the property is set.
4154 public function __isset( $name ) {
4155 if ( in_array( $name, $this->compat_fields ) ) {
4156 return isset( $this->$name );
4161 * Make private/protected methods readable for backwards compatibility.
4166 * @param callable $name Method to call.
4167 * @param array $arguments Arguments to pass when calling.
4168 * @return mixed|false Return value of the callback, false otherwise.
4170 public function __call( $name, $arguments ) {
4171 if ( in_array( $name, $this->compat_methods ) ) {
4172 return call_user_func_array( array( $this, $name ), $arguments );
4178 * Is the query for an existing archive page?
4180 * Month, Year, Category, Author, Post Type archive...
4186 public function is_archive() {
4187 return (bool) $this->is_archive;
4191 * Is the query for an existing post type archive page?
4195 * @param mixed $post_types Optional. Post type or array of posts types to check against.
4198 public function is_post_type_archive( $post_types = '' ) {
4199 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4200 return (bool) $this->is_post_type_archive;
4202 $post_type = $this->get( 'post_type' );
4203 if ( is_array( $post_type ) )
4204 $post_type = reset( $post_type );
4205 $post_type_object = get_post_type_object( $post_type );
4207 return in_array( $post_type_object->name, (array) $post_types );
4211 * Is the query for an existing attachment page?
4215 * @param mixed $attachment Attachment ID, title, slug, or array of such.
4218 public function is_attachment( $attachment = '' ) {
4219 if ( ! $this->is_attachment ) {
4223 if ( empty( $attachment ) ) {
4227 $attachment = (array) $attachment;
4229 $post_obj = $this->get_queried_object();
4231 if ( in_array( (string) $post_obj->ID, $attachment ) ) {
4233 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4235 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4242 * Is the query for an existing author archive page?
4244 * If the $author parameter is specified, this function will additionally
4245 * check if the query is for one of the authors specified.
4249 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4252 public function is_author( $author = '' ) {
4253 if ( !$this->is_author )
4256 if ( empty($author) )
4259 $author_obj = $this->get_queried_object();
4261 $author = (array) $author;
4263 if ( in_array( (string) $author_obj->ID, $author ) )
4265 elseif ( in_array( $author_obj->nickname, $author ) )
4267 elseif ( in_array( $author_obj->user_nicename, $author ) )
4274 * Is the query for an existing category archive page?
4276 * If the $category parameter is specified, this function will additionally
4277 * check if the query is for one of the categories specified.
4281 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4284 public function is_category( $category = '' ) {
4285 if ( !$this->is_category )
4288 if ( empty($category) )
4291 $cat_obj = $this->get_queried_object();
4293 $category = (array) $category;
4295 if ( in_array( (string) $cat_obj->term_id, $category ) )
4297 elseif ( in_array( $cat_obj->name, $category ) )
4299 elseif ( in_array( $cat_obj->slug, $category ) )
4306 * Is the query for an existing tag archive page?
4308 * If the $tag parameter is specified, this function will additionally
4309 * check if the query is for one of the tags specified.
4313 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4316 public function is_tag( $tag = '' ) {
4317 if ( ! $this->is_tag )
4320 if ( empty( $tag ) )
4323 $tag_obj = $this->get_queried_object();
4325 $tag = (array) $tag;
4327 if ( in_array( (string) $tag_obj->term_id, $tag ) )
4329 elseif ( in_array( $tag_obj->name, $tag ) )
4331 elseif ( in_array( $tag_obj->slug, $tag ) )
4338 * Is the query for an existing taxonomy archive page?
4340 * If the $taxonomy parameter is specified, this function will additionally
4341 * check if the query is for that specific $taxonomy.
4343 * If the $term parameter is specified in addition to the $taxonomy parameter,
4344 * this function will additionally check if the query is for one of the terms
4349 * @global array $wp_taxonomies
4351 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4352 * @param mixed $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4355 public function is_tax( $taxonomy = '', $term = '' ) {
4356 global $wp_taxonomies;
4358 if ( !$this->is_tax )
4361 if ( empty( $taxonomy ) )
4364 $queried_object = $this->get_queried_object();
4365 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4366 $term_array = (array) $term;
4368 // Check that the taxonomy matches.
4369 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4372 // Only a Taxonomy provided.
4373 if ( empty( $term ) )
4376 return isset( $queried_object->term_id ) &&
4377 count( array_intersect(
4378 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4384 * Whether the current URL is within the comments popup window.
4390 public function is_comments_popup() {
4391 return (bool) $this->is_comments_popup;
4395 * Is the query for an existing date archive?
4401 public function is_date() {
4402 return (bool) $this->is_date;
4406 * Is the query for an existing day archive?
4412 public function is_day() {
4413 return (bool) $this->is_day;
4417 * Is the query for a feed?
4421 * @param string|array $feeds Optional feed types to check.
4424 public function is_feed( $feeds = '' ) {
4425 if ( empty( $feeds ) || ! $this->is_feed )
4426 return (bool) $this->is_feed;
4427 $qv = $this->get( 'feed' );
4428 if ( 'feed' == $qv )
4429 $qv = get_default_feed();
4430 return in_array( $qv, (array) $feeds );
4434 * Is the query for a comments feed?
4440 public function is_comment_feed() {
4441 return (bool) $this->is_comment_feed;
4445 * Is the query for the front page of the site?
4447 * This is for what is displayed at your site's main URL.
4449 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4451 * If you set a static page for the front page of your site, this function will return
4452 * true when viewing that page.
4454 * Otherwise the same as @see WP_Query::is_home()
4458 * @return bool True, if front of site.
4460 public function is_front_page() {
4462 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4464 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4471 * Is the query for the blog homepage?
4473 * This is the page which shows the time based blog content of your site.
4475 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4477 * If you set a static page for the front page of your site, this function will return
4478 * true only on the page you set as the "Posts page".
4480 * @see WP_Query::is_front_page()
4484 * @return bool True if blog view homepage.
4486 public function is_home() {
4487 return (bool) $this->is_home;
4491 * Is the query for an existing month archive?
4497 public function is_month() {
4498 return (bool) $this->is_month;
4502 * Is the query for an existing single page?
4504 * If the $page parameter is specified, this function will additionally
4505 * check if the query is for one of the pages specified.
4507 * @see WP_Query::is_single()
4508 * @see WP_Query::is_singular()
4512 * @param int|string|array $page Optional. Page ID, title, slug, path, or array of such. Default empty.
4513 * @return bool Whether the query is for an existing single page.
4515 public function is_page( $page = '' ) {
4516 if ( !$this->is_page )
4519 if ( empty( $page ) )
4522 $page_obj = $this->get_queried_object();
4524 $page = (array) $page;
4526 if ( in_array( (string) $page_obj->ID, $page ) ) {
4528 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4530 } elseif ( in_array( $page_obj->post_name, $page ) ) {
4533 foreach ( $page as $pagepath ) {
4534 if ( ! strpos( $pagepath, '/' ) ) {
4537 $pagepath_obj = get_page_by_path( $pagepath );
4539 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4549 * Is the query for paged result and not for the first page?
4555 public function is_paged() {
4556 return (bool) $this->is_paged;
4560 * Is the query for a post or page preview?
4566 public function is_preview() {
4567 return (bool) $this->is_preview;
4571 * Is the query for the robots file?
4577 public function is_robots() {
4578 return (bool) $this->is_robots;
4582 * Is the query for a search?
4588 public function is_search() {
4589 return (bool) $this->is_search;
4593 * Is the query for an existing single post?
4595 * Works for any post type, except attachments and pages
4597 * If the $post parameter is specified, this function will additionally
4598 * check if the query is for one of the Posts specified.
4600 * @see WP_Query::is_page()
4601 * @see WP_Query::is_singular()
4605 * @param int|string|array $post Optional. Post ID, title, slug, path, or array of such. Default empty.
4606 * @return bool Whether the query is for an existing single post.
4608 public function is_single( $post = '' ) {
4609 if ( !$this->is_single )
4615 $post_obj = $this->get_queried_object();
4617 $post = (array) $post;
4619 if ( in_array( (string) $post_obj->ID, $post ) ) {
4621 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4623 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4626 foreach ( $post as $postpath ) {
4627 if ( ! strpos( $postpath, '/' ) ) {
4630 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4632 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4641 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4643 * If the $post_types parameter is specified, this function will additionally
4644 * check if the query is for one of the Posts Types specified.
4646 * @see WP_Query::is_page()
4647 * @see WP_Query::is_single()
4651 * @param string|array $post_types Optional. Post type or array of post types. Default empty.
4652 * @return bool Whether the query is for an existing single post of any of the given post types.
4654 public function is_singular( $post_types = '' ) {
4655 if ( empty( $post_types ) || !$this->is_singular )
4656 return (bool) $this->is_singular;
4658 $post_obj = $this->get_queried_object();
4660 return in_array( $post_obj->post_type, (array) $post_types );
4664 * Is the query for a specific time?
4670 public function is_time() {
4671 return (bool) $this->is_time;
4675 * Is the query for a trackback endpoint call?
4681 public function is_trackback() {
4682 return (bool) $this->is_trackback;
4686 * Is the query for an existing year archive?
4692 public function is_year() {
4693 return (bool) $this->is_year;
4697 * Is the query a 404 (returns no results)?
4703 public function is_404() {
4704 return (bool) $this->is_404;
4708 * Is the query for an embedded post?
4714 public function is_embed() {
4715 return (bool) $this->is_embed;
4719 * Is the query the main query?
4723 * @global WP_Query $wp_query Global WP_Query instance.
4727 public function is_main_query() {
4728 global $wp_the_query;
4729 return $wp_the_query === $this;
4733 * Set up global post data.
4736 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
4739 * @global WP_User $authordata
4740 * @global string|int|bool $currentday
4741 * @global string|int|bool $currentmonth
4743 * @global array $pages
4744 * @global int $multipage
4746 * @global int $numpages
4748 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
4749 * @return true True when finished.
4751 public function setup_postdata( $post ) {
4752 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4754 if ( ! ( $post instanceof WP_Post ) ) {
4755 $post = get_post( $post );
4762 $id = (int) $post->ID;
4764 $authordata = get_userdata($post->post_author);
4766 $currentday = mysql2date('d.m.y', $post->post_date, false);
4767 $currentmonth = mysql2date('m', $post->post_date, false);
4770 $page = $this->get( 'page' );
4775 * Force full post content when viewing the permalink for the $post,
4776 * or when on an RSS feed. Otherwise respect the 'more' tag.
4778 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4780 } elseif ( $this->is_feed() ) {
4786 $content = $post->post_content;
4787 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4788 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4789 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4790 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4792 // Ignore nextpage at the beginning of the content.
4793 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4794 $content = substr( $content, 15 );
4796 $pages = explode('<!--nextpage-->', $content);
4798 $pages = array( $post->post_content );
4802 * Filter the "pages" derived from splitting the post content.
4804 * "Pages" are determined by splitting the post content based on the presence
4805 * of `<!-- nextpage -->` tags.
4809 * @param array $pages Array of "pages" derived from the post content.
4810 * of `<!-- nextpage -->` tags..
4811 * @param WP_Post $post Current post object.
4813 $pages = apply_filters( 'content_pagination', $pages, $post );
4815 $numpages = count( $pages );
4817 if ( $numpages > 1 ) {
4827 * Fires once the post data has been setup.
4830 * @since 4.1.0 Introduced `$this` parameter.
4832 * @param WP_Post &$post The Post object (passed by reference).
4833 * @param WP_Query &$this The current Query object (passed by reference).
4835 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4840 * After looping through a nested query, this function
4841 * restores the $post global to the current post in this query.
4845 * @global WP_Post $post
4847 public function reset_postdata() {
4848 if ( ! empty( $this->post ) ) {
4849 $GLOBALS['post'] = $this->post;
4850 $this->setup_postdata( $this->post );
4855 * Lazy-loads termmeta for located posts.
4857 * As a rule, term queries (`get_terms()` and `wp_get_object_terms()`) prime the metadata cache for matched
4858 * terms by default. However, this can cause a slight performance penalty, especially when that metadata is
4859 * not actually used. In the context of a `WP_Query` instance, we're able to avoid this potential penalty.
4860 * `update_object_term_cache()`, called from `update_post_caches()`, does not 'update_term_meta_cache'.
4861 * Instead, the first time `get_term_meta()` is called from within a `WP_Query` loop, the current method
4862 * detects the fact, and then primes the metadata cache for all terms attached to all posts in the loop,
4863 * with a single database query.
4865 * This method is public so that it can be used as a filter callback. As a rule, there is no need to invoke it
4866 * directly, from either inside or outside the `WP_Query` object.
4871 * @param mixed $check The `$check` param passed from the 'get_term_metadata' hook.
4872 * @param int $term_id ID of the term whose metadata is being cached.
4873 * @return mixed In order not to short-circuit `get_metadata()`. Generally, this is `null`, but it could be
4874 * another value if filtered by a plugin.
4876 public function lazyload_term_meta( $check, $term_id ) {
4878 * We only do this once per `WP_Query` instance.
4879 * Can't use `remove_filter()` because of non-unique object hashes.
4881 if ( $this->updated_term_meta_cache ) {
4885 // We can only lazyload if the entire post object is present.
4887 foreach ( $this->posts as $post ) {
4888 if ( $post instanceof WP_Post ) {
4893 if ( ! empty( $posts ) ) {
4894 // Fetch cached term_ids for each post. Keyed by term_id for faster lookup.
4895 $term_ids = array();
4896 foreach ( $posts as $post ) {
4897 $taxonomies = get_object_taxonomies( $post->post_type );
4898 foreach ( $taxonomies as $taxonomy ) {
4899 // Term cache should already be primed by 'update_post_term_cache'.
4900 $terms = get_object_term_cache( $post->ID, $taxonomy );
4901 if ( false !== $terms ) {
4902 foreach ( $terms as $term ) {
4903 if ( ! isset( $term_ids[ $term->term_id ] ) ) {
4904 $term_ids[ $term->term_id ] = 1;
4912 * Only update the metadata cache for terms belonging to these posts if the term_id passed
4913 * to `get_term_meta()` matches one of those terms. This prevents a single call to
4914 * `get_term_meta()` from priming metadata for all `WP_Query` objects.
4916 if ( isset( $term_ids[ $term_id ] ) ) {
4917 update_termmeta_cache( array_keys( $term_ids ) );
4918 $this->updated_term_meta_cache = true;
4922 // If no terms were found, there's no need to run this again.
4923 if ( empty( $term_ids ) ) {
4924 $this->updated_term_meta_cache = true;
4931 * Lazy-load comment meta when inside of a `WP_Query` loop.
4933 * This method is public so that it can be used as a filter callback. As a rule, there is no need to invoke it
4934 * directly, from either inside or outside the `WP_Query` object.
4938 * @param mixed $check The `$check` param passed from the 'get_comment_metadata' hook.
4939 * @param int $comment_id ID of the comment whose metadata is being cached.
4940 * @return mixed The original value of `$check`, to not affect 'get_comment_metadata'.
4942 public function lazyload_comment_meta( $check, $comment_id ) {
4944 * We only do this once per `WP_Query` instance.
4945 * Can't use `remove_filter()` because of non-unique object hashes.
4947 if ( $this->updated_comment_meta_cache ) {
4951 // Don't use `wp_list_pluck()` to avoid by-reference manipulation.
4952 $comment_ids = array();
4953 if ( is_array( $this->comments ) ) {
4954 foreach ( $this->comments as $comment ) {
4955 $comment_ids[] = $comment->comment_ID;
4960 * Only update the metadata cache for comments belonging to these posts if the comment_id passed
4961 * to `get_comment_meta()` matches one of those comments. This prevents a single call to
4962 * `get_comment_meta()` from priming metadata for all `WP_Query` objects.
4964 if ( in_array( $comment_id, $comment_ids ) ) {
4965 update_meta_cache( 'comment', $comment_ids );
4966 $this->updated_comment_meta_cache = true;
4967 } elseif ( empty( $comment_ids ) ) {
4968 $this->updated_comment_meta_cache = true;
4976 * Redirect old slugs to the correct permalink.
4978 * Attempts to find the current slug from the past slugs.
4982 * @global WP_Query $wp_query Global WP_Query instance.
4983 * @global wpdb $wpdb WordPress database abstraction object.
4984 * @global WP_Rewrite $wp_rewrite WordPress rewrite component.
4986 function wp_old_slug_redirect() {
4987 global $wp_query, $wp_rewrite;
4989 if ( '' !== $wp_query->query_vars['name'] ) :
4992 // Guess the current post_type based on the query vars.
4993 if ( get_query_var( 'post_type' ) ) {
4994 $post_type = get_query_var( 'post_type' );
4995 } elseif ( get_query_var( 'attachment' ) ) {
4996 $post_type = 'attachment';
4997 } elseif ( ! empty( $wp_query->query_vars['pagename'] ) ) {
4998 $post_type = 'page';
5000 $post_type = 'post';
5003 if ( is_array( $post_type ) ) {
5004 if ( count( $post_type ) > 1 )
5006 $post_type = reset( $post_type );
5009 // Do not attempt redirect for hierarchical post types
5010 if ( is_post_type_hierarchical( $post_type ) )
5013 $query = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND post_type = %s AND meta_key = '_wp_old_slug' AND meta_value = %s", $post_type, $wp_query->query_vars['name']);
5015 // if year, monthnum, or day have been specified, make our query more precise
5016 // just in case there are multiple identical _wp_old_slug values
5017 if ( '' != $wp_query->query_vars['year'] )
5018 $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
5019 if ( '' != $wp_query->query_vars['monthnum'] )
5020 $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
5021 if ( '' != $wp_query->query_vars['day'] )
5022 $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
5024 $id = (int) $wpdb->get_var($query);
5029 $link = get_permalink( $id );
5032 $link = user_trailingslashit( trailingslashit( $link ) . 'feed' );
5033 } elseif ( isset( $GLOBALS['wp_query']->query_vars['paged'] ) && $GLOBALS['wp_query']->query_vars['paged'] > 1 ) {
5034 $link = user_trailingslashit( trailingslashit( $link ) . 'page/' . $GLOBALS['wp_query']->query_vars['paged'] );
5035 } elseif( is_embed() ) {
5036 $link = user_trailingslashit( trailingslashit( $link ) . 'embed' );
5037 } elseif ( is_404() ) {
5038 // Add rewrite endpoints if necessary.
5039 foreach ( $wp_rewrite->endpoints as $endpoint ) {
5040 if ( $endpoint[2] && false !== get_query_var( $endpoint[2], false ) ) {
5041 $link = user_trailingslashit( trailingslashit( $link ) . $endpoint[1] );
5047 * Filter the old slug redirect URL.
5051 * @param string $link The redirect URL.
5053 $link = apply_filters( 'old_slug_redirect_url', $link );
5059 wp_redirect( $link, 301 ); // Permanent redirect
5065 * Set up global post data.
5068 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
5070 * @global WP_Query $wp_query Global WP_Query instance.
5072 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
5073 * @return bool True when finished.
5075 function setup_postdata( $post ) {
5078 if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
5079 return $wp_query->setup_postdata( $post );