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 * Sets up The Loop with query parameters.
82 * Note: This function will completely override the main query and isn't intended for use
83 * by plugins or themes. Its overly-simplistic approach to modifying the main query can be
84 * problematic and should be avoided wherever possible. In most cases, there are better,
85 * more performant options for modifying the main query such as via the {@see 'pre_get_posts'}
86 * action within WP_Query.
88 * This must not be used within the WordPress Loop.
92 * @global WP_Query $wp_query Global WP_Query instance.
94 * @param array|string $query Array or string of WP_Query arguments.
95 * @return array List of post objects.
97 function query_posts($query) {
98 $GLOBALS['wp_query'] = new WP_Query();
99 return $GLOBALS['wp_query']->query($query);
103 * Destroys the previous query and sets up a new query.
105 * This should be used after query_posts() and before another query_posts().
106 * This will remove obscure bugs that occur when the previous WP_Query object
107 * is not destroyed properly before another is set up.
111 * @global WP_Query $wp_query Global WP_Query instance.
112 * @global WP_Query $wp_the_query Copy of the global WP_Query instance created during wp_reset_query().
114 function wp_reset_query() {
115 $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
120 * After looping through a separate query, this function restores
121 * the $post global to the current post in the main query.
125 * @global WP_Query $wp_query Global WP_Query instance.
127 function wp_reset_postdata() {
130 if ( isset( $wp_query ) ) {
131 $wp_query->reset_postdata();
140 * Is the query for an existing archive page?
142 * Month, Year, Category, Author, Post Type archive...
146 * @global WP_Query $wp_query Global WP_Query instance.
150 function is_archive() {
153 if ( ! isset( $wp_query ) ) {
154 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
158 return $wp_query->is_archive();
162 * Is the query for an existing post type archive page?
166 * @global WP_Query $wp_query Global WP_Query instance.
168 * @param string|array $post_types Optional. Post type or array of posts types to check against.
171 function is_post_type_archive( $post_types = '' ) {
174 if ( ! isset( $wp_query ) ) {
175 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
179 return $wp_query->is_post_type_archive( $post_types );
183 * Is the query for an existing attachment page?
187 * @global WP_Query $wp_query Global WP_Query instance.
189 * @param int|string|array|object $attachment Attachment ID, title, slug, or array of such.
192 function is_attachment( $attachment = '' ) {
195 if ( ! isset( $wp_query ) ) {
196 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
200 return $wp_query->is_attachment( $attachment );
204 * Is the query for an existing author archive page?
206 * If the $author parameter is specified, this function will additionally
207 * check if the query is for one of the authors specified.
211 * @global WP_Query $wp_query Global WP_Query instance.
213 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
216 function is_author( $author = '' ) {
219 if ( ! isset( $wp_query ) ) {
220 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
224 return $wp_query->is_author( $author );
228 * Is the query for an existing category archive page?
230 * If the $category parameter is specified, this function will additionally
231 * check if the query is for one of the categories specified.
235 * @global WP_Query $wp_query Global WP_Query instance.
237 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
240 function is_category( $category = '' ) {
243 if ( ! isset( $wp_query ) ) {
244 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
248 return $wp_query->is_category( $category );
252 * Is the query for an existing tag archive page?
254 * If the $tag parameter is specified, this function will additionally
255 * check if the query is for one of the tags specified.
259 * @global WP_Query $wp_query Global WP_Query instance.
261 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
264 function is_tag( $tag = '' ) {
267 if ( ! isset( $wp_query ) ) {
268 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
272 return $wp_query->is_tag( $tag );
276 * Is the query for an existing custom taxonomy archive page?
278 * If the $taxonomy parameter is specified, this function will additionally
279 * check if the query is for that specific $taxonomy.
281 * If the $term parameter is specified in addition to the $taxonomy parameter,
282 * this function will additionally check if the query is for one of the terms
287 * @global WP_Query $wp_query Global WP_Query instance.
289 * @param string|array $taxonomy Optional. Taxonomy slug or slugs.
290 * @param int|string|array $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
291 * @return bool True for custom taxonomy archive pages, false for built-in taxonomies (category and tag archives).
293 function is_tax( $taxonomy = '', $term = '' ) {
296 if ( ! isset( $wp_query ) ) {
297 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
301 return $wp_query->is_tax( $taxonomy, $term );
305 * Is the query for an existing date archive?
309 * @global WP_Query $wp_query Global WP_Query instance.
316 if ( ! isset( $wp_query ) ) {
317 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
321 return $wp_query->is_date();
325 * Is the query for an existing day archive?
329 * @global WP_Query $wp_query Global WP_Query instance.
336 if ( ! isset( $wp_query ) ) {
337 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
341 return $wp_query->is_day();
345 * Is the query for a feed?
349 * @global WP_Query $wp_query Global WP_Query instance.
351 * @param string|array $feeds Optional feed types to check.
354 function is_feed( $feeds = '' ) {
357 if ( ! isset( $wp_query ) ) {
358 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
362 return $wp_query->is_feed( $feeds );
366 * Is the query for a comments feed?
370 * @global WP_Query $wp_query Global WP_Query instance.
374 function is_comment_feed() {
377 if ( ! isset( $wp_query ) ) {
378 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
382 return $wp_query->is_comment_feed();
386 * Is the query for the front page of the site?
388 * This is for what is displayed at your site's main URL.
390 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
392 * If you set a static page for the front page of your site, this function will return
393 * true when viewing that page.
395 * Otherwise the same as @see is_home()
399 * @global WP_Query $wp_query Global WP_Query instance.
401 * @return bool True, if front of site.
403 function is_front_page() {
406 if ( ! isset( $wp_query ) ) {
407 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
411 return $wp_query->is_front_page();
415 * Determines if the query is for the blog homepage.
417 * The blog homepage is the page that shows the time-based blog content of the site.
419 * is_home() is dependent on the site's "Front page displays" Reading Settings 'show_on_front'
420 * and 'page_for_posts'.
422 * If a static page is set for the front page of the site, this function will return true only
423 * on the page you set as the "Posts page".
427 * @see is_front_page()
428 * @global WP_Query $wp_query Global WP_Query instance.
430 * @return bool True if blog view homepage, otherwise false.
435 if ( ! isset( $wp_query ) ) {
436 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
440 return $wp_query->is_home();
444 * Is the query for an existing month archive?
448 * @global WP_Query $wp_query Global WP_Query instance.
452 function is_month() {
455 if ( ! isset( $wp_query ) ) {
456 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
460 return $wp_query->is_month();
464 * Is the query for an existing single page?
466 * If the $page parameter is specified, this function will additionally
467 * check if the query is for one of the pages specified.
474 * @global WP_Query $wp_query Global WP_Query instance.
476 * @param int|string|array $page Optional. Page ID, title, slug, or array of such. Default empty.
477 * @return bool Whether the query is for an existing single page.
479 function is_page( $page = '' ) {
482 if ( ! isset( $wp_query ) ) {
483 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
487 return $wp_query->is_page( $page );
491 * Is the query for paged result and not for the first page?
495 * @global WP_Query $wp_query Global WP_Query instance.
499 function is_paged() {
502 if ( ! isset( $wp_query ) ) {
503 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
507 return $wp_query->is_paged();
511 * Is the query for a post or page preview?
515 * @global WP_Query $wp_query Global WP_Query instance.
519 function is_preview() {
522 if ( ! isset( $wp_query ) ) {
523 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
527 return $wp_query->is_preview();
531 * Is the query for the robots file?
535 * @global WP_Query $wp_query Global WP_Query instance.
539 function is_robots() {
542 if ( ! isset( $wp_query ) ) {
543 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
547 return $wp_query->is_robots();
551 * Is the query for a search?
555 * @global WP_Query $wp_query Global WP_Query instance.
559 function is_search() {
562 if ( ! isset( $wp_query ) ) {
563 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
567 return $wp_query->is_search();
571 * Is the query for an existing single post?
573 * Works for any post type, except attachments and pages
575 * If the $post parameter is specified, this function will additionally
576 * check if the query is for one of the Posts specified.
583 * @global WP_Query $wp_query Global WP_Query instance.
585 * @param int|string|array $post Optional. Post ID, title, slug, or array of such. Default empty.
586 * @return bool Whether the query is for an existing single post.
588 function is_single( $post = '' ) {
591 if ( ! isset( $wp_query ) ) {
592 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
596 return $wp_query->is_single( $post );
600 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
602 * If the $post_types parameter is specified, this function will additionally
603 * check if the query is for one of the Posts Types specified.
610 * @global WP_Query $wp_query Global WP_Query instance.
612 * @param string|array $post_types Optional. Post type or array of post types. Default empty.
613 * @return bool Whether the query is for an existing single post of any of the given post types.
615 function is_singular( $post_types = '' ) {
618 if ( ! isset( $wp_query ) ) {
619 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
623 return $wp_query->is_singular( $post_types );
627 * Is the query for a specific time?
631 * @global WP_Query $wp_query Global WP_Query instance.
638 if ( ! isset( $wp_query ) ) {
639 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
643 return $wp_query->is_time();
647 * Is the query for a trackback endpoint call?
651 * @global WP_Query $wp_query Global WP_Query instance.
655 function is_trackback() {
658 if ( ! isset( $wp_query ) ) {
659 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
663 return $wp_query->is_trackback();
667 * Is the query for an existing year archive?
671 * @global WP_Query $wp_query Global WP_Query instance.
678 if ( ! isset( $wp_query ) ) {
679 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
683 return $wp_query->is_year();
687 * Is the query a 404 (returns no results)?
691 * @global WP_Query $wp_query Global WP_Query instance.
698 if ( ! isset( $wp_query ) ) {
699 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
703 return $wp_query->is_404();
707 * Is the query for an embedded post?
711 * @global WP_Query $wp_query Global WP_Query instance.
713 * @return bool Whether we're in an embedded post or not.
715 function is_embed() {
718 if ( ! isset( $wp_query ) ) {
719 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1.0' );
723 return $wp_query->is_embed();
727 * Is the query the main query?
731 * @global WP_Query $wp_query Global WP_Query instance.
735 function is_main_query() {
736 if ( 'pre_get_posts' === current_filter() ) {
738 /* translators: 1: pre_get_posts 2: WP_Query->is_main_query() 3: is_main_query() 4: link to codex is_main_query() page. */
739 __( 'In %1$s, use the %2$s method, not the %3$s function. See %4$s.' ),
740 '<code>pre_get_posts</code>',
741 '<code>WP_Query->is_main_query()</code>',
742 '<code>is_main_query()</code>',
743 __( 'https://codex.wordpress.org/Function_Reference/is_main_query' )
745 _doing_it_wrong( __FUNCTION__, $message, '3.7.0' );
749 return $wp_query->is_main_query();
753 * The Loop. Post loop control.
757 * Whether current WordPress query has results to loop over.
761 * @global WP_Query $wp_query Global WP_Query instance.
765 function have_posts() {
767 return $wp_query->have_posts();
771 * Whether the caller is in the Loop.
775 * @global WP_Query $wp_query Global WP_Query instance.
777 * @return bool True if caller is within loop, false if loop hasn't started or ended.
779 function in_the_loop() {
781 return $wp_query->in_the_loop;
785 * Rewind the loop posts.
789 * @global WP_Query $wp_query Global WP_Query instance.
791 function rewind_posts() {
793 $wp_query->rewind_posts();
797 * Iterate the post index in the loop.
801 * @global WP_Query $wp_query Global WP_Query instance.
803 function the_post() {
805 $wp_query->the_post();
813 * Whether there are comments to loop over.
817 * @global WP_Query $wp_query Global WP_Query instance.
821 function have_comments() {
823 return $wp_query->have_comments();
827 * Iterate comment index in the comment loop.
831 * @global WP_Query $wp_query Global WP_Query instance.
835 function the_comment() {
837 return $wp_query->the_comment();
845 * The WordPress Query class.
847 * @link https://codex.wordpress.org/Function_Reference/WP_Query Codex page.
850 * @since 4.5.0 Removed the `$comments_popup` property.
855 * Query vars set by the user
864 * Query vars, after parsing
870 public $query_vars = array();
873 * Taxonomy query, as passed to get_tax_sql()
877 * @var object WP_Tax_Query
882 * Metadata query container
886 * @var object WP_Meta_Query
888 public $meta_query = false;
891 * Date query container
895 * @var object WP_Date_Query
897 public $date_query = false;
900 * Holds the data for a single object that is queried.
902 * Holds the contents of a post, page, category, attachment.
908 public $queried_object;
911 * The ID of the queried object.
917 public $queried_object_id;
920 * Get post database query.
938 * The amount of posts for the current query.
944 public $post_count = 0;
947 * Index of the current item in the loop.
953 public $current_post = -1;
956 * Whether the loop has started and the caller is in the loop.
962 public $in_the_loop = false;
974 * The list of comments for current post.
983 * The amount of comments for the posts.
989 public $comment_count = 0;
992 * The index of the comment in the comment loop.
998 public $current_comment = -1;
1001 * Current comment ID.
1010 * The amount of found posts for the current query.
1012 * If limit clause was not used, equals $post_count.
1018 public $found_posts = 0;
1021 * The amount of pages.
1027 public $max_num_pages = 0;
1030 * The amount of comment pages.
1036 public $max_num_comment_pages = 0;
1039 * Set if query is single post.
1045 public $is_single = false;
1048 * Set if query is preview of blog.
1054 public $is_preview = false;
1057 * Set if query returns a page.
1063 public $is_page = false;
1066 * Set if query is an archive list.
1072 public $is_archive = false;
1075 * Set if query is part of a date.
1081 public $is_date = false;
1084 * Set if query contains a year.
1090 public $is_year = false;
1093 * Set if query contains a month.
1099 public $is_month = false;
1102 * Set if query contains a day.
1108 public $is_day = false;
1111 * Set if query contains time.
1117 public $is_time = false;
1120 * Set if query contains an author.
1126 public $is_author = false;
1129 * Set if query contains category.
1135 public $is_category = false;
1138 * Set if query contains tag.
1144 public $is_tag = false;
1147 * Set if query contains taxonomy.
1153 public $is_tax = false;
1156 * Set if query was part of a search result.
1162 public $is_search = false;
1165 * Set if query is feed display.
1171 public $is_feed = false;
1174 * Set if query is comment feed display.
1180 public $is_comment_feed = false;
1183 * Set if query is trackback.
1189 public $is_trackback = false;
1192 * Set if query is blog homepage.
1198 public $is_home = false;
1201 * Set if query couldn't found anything.
1207 public $is_404 = false;
1210 * Set if query is embed.
1216 public $is_embed = false;
1219 * Set if query is paged
1225 public $is_paged = false;
1228 * Set if query is part of administration page.
1234 public $is_admin = false;
1237 * Set if query is an attachment.
1243 public $is_attachment = false;
1246 * Set if is single, is a page, or is an attachment.
1252 public $is_singular = false;
1255 * Set if query is for robots.
1261 public $is_robots = false;
1264 * Set if query contains posts.
1266 * Basically, the homepage if the option isn't set for the static homepage.
1272 public $is_posts_page = false;
1275 * Set if query is for a post type archive.
1281 public $is_post_type_archive = false;
1284 * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
1285 * whether we have to re-parse because something has changed
1291 private $query_vars_hash = false;
1294 * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
1295 * via pre_get_posts hooks.
1300 private $query_vars_changed = true;
1303 * Set if post thumbnails are cached
1309 public $thumbnails_cached = false;
1312 * Cached list of search stopwords.
1319 private $compat_fields = array( 'query_vars_hash', 'query_vars_changed' );
1321 private $compat_methods = array( 'init_query_flags', 'parse_tax_query' );
1324 * Resets query flags to false.
1326 * The query flags are what page info WordPress was able to figure out.
1331 private function init_query_flags() {
1332 $this->is_single = false;
1333 $this->is_preview = false;
1334 $this->is_page = false;
1335 $this->is_archive = false;
1336 $this->is_date = false;
1337 $this->is_year = false;
1338 $this->is_month = false;
1339 $this->is_day = false;
1340 $this->is_time = false;
1341 $this->is_author = false;
1342 $this->is_category = false;
1343 $this->is_tag = false;
1344 $this->is_tax = false;
1345 $this->is_search = false;
1346 $this->is_feed = false;
1347 $this->is_comment_feed = false;
1348 $this->is_trackback = false;
1349 $this->is_home = false;
1350 $this->is_404 = false;
1351 $this->is_paged = false;
1352 $this->is_admin = false;
1353 $this->is_attachment = false;
1354 $this->is_singular = false;
1355 $this->is_robots = false;
1356 $this->is_posts_page = false;
1357 $this->is_post_type_archive = false;
1361 * Initiates object properties and sets default values.
1366 public function init() {
1367 unset($this->posts);
1368 unset($this->query);
1369 $this->query_vars = array();
1370 unset($this->queried_object);
1371 unset($this->queried_object_id);
1372 $this->post_count = 0;
1373 $this->current_post = -1;
1374 $this->in_the_loop = false;
1375 unset( $this->request );
1376 unset( $this->post );
1377 unset( $this->comments );
1378 unset( $this->comment );
1379 $this->comment_count = 0;
1380 $this->current_comment = -1;
1381 $this->found_posts = 0;
1382 $this->max_num_pages = 0;
1383 $this->max_num_comment_pages = 0;
1385 $this->init_query_flags();
1389 * Reparse the query vars.
1394 public function parse_query_vars() {
1395 $this->parse_query();
1399 * Fills in the query variables, which do not exist within the parameter.
1402 * @since 4.4.0 Removed the `comments_popup` public query variable.
1405 * @param array $array Defined query variables.
1406 * @return array Complete query variables with undefined ones filled in empty.
1408 public function fill_query_vars($array) {
1449 foreach ( $keys as $key ) {
1450 if ( !isset($array[$key]) )
1454 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in', 'post_name__in',
1455 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
1456 'author__in', 'author__not_in' );
1458 foreach ( $array_keys as $key ) {
1459 if ( !isset($array[$key]) )
1460 $array[$key] = array();
1466 * Parse a query string and set query type booleans.
1469 * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
1470 * array key to `$orderby`.
1471 * @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
1472 * search terms, by prepending a hyphen.
1473 * @since 4.5.0 Removed the `$comments_popup` parameter.
1474 * Introduced the `$comment_status` and `$ping_status` parameters.
1475 * Introduced `RAND(x)` syntax for `$orderby`, which allows an integer seed value to random sorts.
1476 * @since 4.6.0 Added 'post_name__in' support for `$orderby`. Introduced the `$lazy_load_term_meta` argument.
1479 * @param string|array $query {
1480 * Optional. Array or string of Query parameters.
1482 * @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
1483 * @type int|string $author Author ID, or comma-separated list of IDs.
1484 * @type string $author_name User 'user_nicename'.
1485 * @type array $author__in An array of author IDs to query from.
1486 * @type array $author__not_in An array of author IDs not to query from.
1487 * @type bool $cache_results Whether to cache post information. Default true.
1488 * @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
1489 * @type array $category__and An array of category IDs (AND in).
1490 * @type array $category__in An array of category IDs (OR in, no children).
1491 * @type array $category__not_in An array of category IDs (NOT in).
1492 * @type string $category_name Use category slug (not name, this or any children).
1493 * @type string $comment_status Comment status.
1494 * @type int $comments_per_page The number of comments to return per page.
1495 * Default 'comments_per_page' option.
1496 * @type array $date_query An associative array of WP_Date_Query arguments.
1497 * See WP_Date_Query::__construct().
1498 * @type int $day Day of the month. Default empty. Accepts numbers 1-31.
1499 * @type bool $exact Whether to search by exact keyword. Default false.
1500 * @type string|array $fields Which fields to return. Single field or all fields (string),
1501 * or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
1502 * Default all fields. Accepts 'ids', 'id=>parent'.
1503 * @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
1504 * @type int|bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
1505 * excludes stickies from 'post__in'. Accepts 1|true, 0|false.
1507 * @type int $m Combination YearMonth. Accepts any four-digit year and month
1508 * numbers 1-12. Default empty.
1509 * @type string $meta_compare Comparison operator to test the 'meta_value'.
1510 * @type string $meta_key Custom field key.
1511 * @type array $meta_query An associative array of WP_Meta_Query arguments. See WP_Meta_Query.
1512 * @type string $meta_value Custom field value.
1513 * @type int $meta_value_num Custom field value number.
1514 * @type int $menu_order The menu order of the posts.
1515 * @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
1516 * @type string $name Post slug.
1517 * @type bool $nopaging Show all posts (true) or paginate (false). Default false.
1518 * @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
1519 * performance. Default false.
1520 * @type int $offset The number of posts to offset before retrieval.
1521 * @type string $order Designates ascending or descending order of posts. Default 'DESC'.
1522 * Accepts 'ASC', 'DESC'.
1523 * @type string|array $orderby Sort retrieved posts by parameter. One or more options may be
1524 * passed. To use 'meta_value', or 'meta_value_num',
1525 * 'meta_key=keyname' must be also be defined. To sort by a
1526 * specific `$meta_query` clause, use that clause's array key.
1527 * Default 'date'. Accepts 'none', 'name', 'author', 'date',
1528 * 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand',
1529 * 'RAND(x)' (where 'x' is an integer seed value),
1530 * 'comment_count', 'meta_value', 'meta_value_num', 'post__in',
1531 * 'post_name__in', 'post_parent__in', and the array keys
1533 * @type int $p Post ID.
1534 * @type int $page Show the number of posts that would show up on page X of a
1535 * static front page.
1536 * @type int $paged The number of the current page.
1537 * @type int $page_id Page ID.
1538 * @type string $pagename Page slug.
1539 * @type string $perm Show posts if user has the appropriate capability.
1540 * @type string $ping_status Ping status.
1541 * @type array $post__in An array of post IDs to retrieve, sticky posts will be included
1542 * @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
1543 * @type array $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
1544 * separated IDs will NOT work.
1545 * @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
1547 * @type array $post_parent__in An array containing parent page IDs to query child pages from.
1548 * @type array $post_parent__not_in An array containing parent page IDs not to query child pages from.
1549 * @type string|array $post_type A post type slug (string) or array of post type slugs.
1550 * Default 'any' if using 'tax_query'.
1551 * @type string|array $post_status A post status (string) or array of post statuses.
1552 * @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
1553 * @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
1554 * 'posts_per_page' when is_archive(), or is_search() are true.
1555 * @type array $post_name__in An array of post slugs that results must match.
1556 * @type string $s Search keyword(s). Prepending a term with a hyphen will
1557 * exclude posts matching that term. Eg, 'pillow -sofa' will
1558 * return posts containing 'pillow' but not 'sofa'.
1559 * @type int $second Second of the minute. Default empty. Accepts numbers 0-60.
1560 * @type bool $sentence Whether to search by phrase. Default false.
1561 * @type bool $suppress_filters Whether to suppress filters. Default false.
1562 * @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
1563 * @type array $tag__and An array of tag ids (AND in).
1564 * @type array $tag__in An array of tag ids (OR in).
1565 * @type array $tag__not_in An array of tag ids (NOT in).
1566 * @type int $tag_id Tag id or comma-separated list of IDs.
1567 * @type array $tag_slug__and An array of tag slugs (AND in).
1568 * @type array $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
1569 * true. Note: a string of comma-separated IDs will NOT work.
1570 * @type array $tax_query An associative array of WP_Tax_Query arguments.
1571 * See WP_Tax_Query->queries.
1572 * @type string $title Post title.
1573 * @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
1574 * @type bool $update_post_term_cache Whether to update the post term cache. Default true.
1575 * @type bool $lazy_load_term_meta Whether to lazy-load term meta. Setting to false will
1576 * disable cache priming for term meta, so that each
1577 * get_term_meta() call will hit the database.
1578 * Defaults to the value of `$update_post_term_cache`.
1579 * @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
1580 * @type int $year The four-digit year. Default empty. Accepts any four-digit year.
1583 public function parse_query( $query = '' ) {
1584 if ( ! empty( $query ) ) {
1586 $this->query = $this->query_vars = wp_parse_args( $query );
1587 } elseif ( ! isset( $this->query ) ) {
1588 $this->query = $this->query_vars;
1591 $this->query_vars = $this->fill_query_vars($this->query_vars);
1592 $qv = &$this->query_vars;
1593 $this->query_vars_changed = true;
1595 if ( ! empty($qv['robots']) )
1596 $this->is_robots = true;
1598 $qv['p'] = absint($qv['p']);
1599 $qv['page_id'] = absint($qv['page_id']);
1600 $qv['year'] = absint($qv['year']);
1601 $qv['monthnum'] = absint($qv['monthnum']);
1602 $qv['day'] = absint($qv['day']);
1603 $qv['w'] = absint($qv['w']);
1604 $qv['m'] = is_scalar( $qv['m'] ) ? preg_replace( '|[^0-9]|', '', $qv['m'] ) : '';
1605 $qv['paged'] = absint($qv['paged']);
1606 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1607 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
1608 $qv['pagename'] = trim( $qv['pagename'] );
1609 $qv['name'] = trim( $qv['name'] );
1610 $qv['title'] = trim( $qv['title'] );
1611 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1612 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1613 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1614 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
1616 // Fairly insane upper bound for search string lengths.
1617 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
1621 // Compat. Map subpost to attachment.
1622 if ( '' != $qv['subpost'] )
1623 $qv['attachment'] = $qv['subpost'];
1624 if ( '' != $qv['subpost_id'] )
1625 $qv['attachment_id'] = $qv['subpost_id'];
1627 $qv['attachment_id'] = absint($qv['attachment_id']);
1629 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1630 $this->is_single = true;
1631 $this->is_attachment = true;
1632 } elseif ( '' != $qv['name'] ) {
1633 $this->is_single = true;
1634 } elseif ( $qv['p'] ) {
1635 $this->is_single = true;
1636 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1637 // If year, month, day, hour, minute, and second are set, a single
1638 // post is being queried.
1639 $this->is_single = true;
1640 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1641 $this->is_page = true;
1642 $this->is_single = false;
1644 // Look for archive queries. Dates, categories, authors, search, post type archives.
1646 if ( isset( $this->query['s'] ) ) {
1647 $this->is_search = true;
1650 if ( '' !== $qv['second'] ) {
1651 $this->is_time = true;
1652 $this->is_date = true;
1655 if ( '' !== $qv['minute'] ) {
1656 $this->is_time = true;
1657 $this->is_date = true;
1660 if ( '' !== $qv['hour'] ) {
1661 $this->is_time = true;
1662 $this->is_date = true;
1666 if ( ! $this->is_date ) {
1667 $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
1668 if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
1669 $qv['error'] = '404';
1671 $this->is_day = true;
1672 $this->is_date = true;
1677 if ( $qv['monthnum'] ) {
1678 if ( ! $this->is_date ) {
1679 if ( 12 < $qv['monthnum'] ) {
1680 $qv['error'] = '404';
1682 $this->is_month = true;
1683 $this->is_date = true;
1688 if ( $qv['year'] ) {
1689 if ( ! $this->is_date ) {
1690 $this->is_year = true;
1691 $this->is_date = true;
1696 $this->is_date = true;
1697 if ( strlen($qv['m']) > 9 ) {
1698 $this->is_time = true;
1699 } elseif ( strlen( $qv['m'] ) > 7 ) {
1700 $this->is_day = true;
1701 } elseif ( strlen( $qv['m'] ) > 5 ) {
1702 $this->is_month = true;
1704 $this->is_year = true;
1708 if ( '' != $qv['w'] ) {
1709 $this->is_date = true;
1712 $this->query_vars_hash = false;
1713 $this->parse_tax_query( $qv );
1715 foreach ( $this->tax_query->queries as $tax_query ) {
1716 if ( ! is_array( $tax_query ) ) {
1720 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
1721 switch ( $tax_query['taxonomy'] ) {
1723 $this->is_category = true;
1726 $this->is_tag = true;
1729 $this->is_tax = true;
1733 unset( $tax_query );
1735 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1736 $this->is_author = false;
1738 $this->is_author = true;
1741 if ( '' != $qv['author_name'] )
1742 $this->is_author = true;
1744 if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
1745 $post_type_obj = get_post_type_object( $qv['post_type'] );
1746 if ( ! empty( $post_type_obj->has_archive ) )
1747 $this->is_post_type_archive = true;
1750 if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
1751 $this->is_archive = true;
1754 if ( '' != $qv['feed'] )
1755 $this->is_feed = true;
1757 if ( '' != $qv['embed'] ) {
1758 $this->is_embed = true;
1761 if ( '' != $qv['tb'] )
1762 $this->is_trackback = true;
1764 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
1765 $this->is_paged = true;
1767 // if we're previewing inside the write screen
1768 if ( '' != $qv['preview'] )
1769 $this->is_preview = true;
1772 $this->is_admin = true;
1774 if ( false !== strpos($qv['feed'], 'comments-') ) {
1775 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1776 $qv['withcomments'] = 1;
1779 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1781 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1782 $this->is_comment_feed = true;
1784 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_robots ) )
1785 $this->is_home = true;
1787 // Correct is_* for page_on_front and page_for_posts
1788 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1789 $_query = wp_parse_args($this->query);
1790 // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
1791 if ( isset($_query['pagename']) && '' == $_query['pagename'] )
1792 unset($_query['pagename']);
1794 unset( $_query['embed'] );
1796 if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
1797 $this->is_page = true;
1798 $this->is_home = false;
1799 $qv['page_id'] = get_option('page_on_front');
1800 // Correct <!--nextpage--> for page_on_front
1801 if ( !empty($qv['paged']) ) {
1802 $qv['page'] = $qv['paged'];
1803 unset($qv['paged']);
1808 if ( '' != $qv['pagename'] ) {
1809 $this->queried_object = get_page_by_path( $qv['pagename'] );
1811 if ( $this->queried_object && 'attachment' == $this->queried_object->post_type ) {
1812 if ( preg_match( "/^[^%]*%(?:postname)%/", get_option( 'permalink_structure' ) ) ) {
1813 // See if we also have a post with the same slug
1814 $post = get_page_by_path( $qv['pagename'], OBJECT, 'post' );
1816 $this->queried_object = $post;
1817 $this->is_page = false;
1818 $this->is_single = true;
1823 if ( ! empty( $this->queried_object ) ) {
1824 $this->queried_object_id = (int) $this->queried_object->ID;
1826 unset( $this->queried_object );
1829 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1830 $this->is_page = false;
1831 $this->is_home = true;
1832 $this->is_posts_page = true;
1836 if ( $qv['page_id'] ) {
1837 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1838 $this->is_page = false;
1839 $this->is_home = true;
1840 $this->is_posts_page = true;
1844 if ( !empty($qv['post_type']) ) {
1845 if ( is_array($qv['post_type']) )
1846 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1848 $qv['post_type'] = sanitize_key($qv['post_type']);
1851 if ( ! empty( $qv['post_status'] ) ) {
1852 if ( is_array( $qv['post_status'] ) )
1853 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1855 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1858 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1859 $this->is_comment_feed = false;
1861 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1862 // Done correcting is_* for page_on_front and page_for_posts
1864 if ( '404' == $qv['error'] )
1867 $this->is_embed = $this->is_embed && ( $this->is_singular || $this->is_404 );
1869 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1870 $this->query_vars_changed = false;
1873 * Fires after the main query vars have been parsed.
1877 * @param WP_Query &$this The WP_Query instance (passed by reference).
1879 do_action_ref_array( 'parse_query', array( &$this ) );
1883 * Parses various taxonomy related query vars.
1885 * For BC, this method is not marked as protected. See [28987].
1890 * @param array $q The query variables. Passed by reference.
1892 public function parse_tax_query( &$q ) {
1893 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1894 $tax_query = $q['tax_query'];
1896 $tax_query = array();
1899 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1900 $tax_query[] = array(
1901 'taxonomy' => $q['taxonomy'],
1902 'terms' => array( $q['term'] ),
1907 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1908 if ( 'post_tag' == $taxonomy )
1909 continue; // Handled further down in the $q['tag'] block
1911 if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1912 $tax_query_defaults = array(
1913 'taxonomy' => $taxonomy,
1917 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1918 $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1921 $term = $q[$t->query_var];
1923 if ( is_array( $term ) ) {
1924 $term = implode( ',', $term );
1927 if ( strpos($term, '+') !== false ) {
1928 $terms = preg_split( '/[+]+/', $term );
1929 foreach ( $terms as $term ) {
1930 $tax_query[] = array_merge( $tax_query_defaults, array(
1931 'terms' => array( $term )
1935 $tax_query[] = array_merge( $tax_query_defaults, array(
1936 'terms' => preg_split( '/[,]+/', $term )
1942 // If querystring 'cat' is an array, implode it.
1943 if ( is_array( $q['cat'] ) ) {
1944 $q['cat'] = implode( ',', $q['cat'] );
1948 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1949 $cat_in = $cat_not_in = array();
1951 $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1952 $cat_array = array_map( 'intval', $cat_array );
1953 $q['cat'] = implode( ',', $cat_array );
1955 foreach ( $cat_array as $cat ) {
1959 $cat_not_in[] = abs( $cat );
1962 if ( ! empty( $cat_in ) ) {
1963 $tax_query[] = array(
1964 'taxonomy' => 'category',
1966 'field' => 'term_id',
1967 'include_children' => true
1971 if ( ! empty( $cat_not_in ) ) {
1972 $tax_query[] = array(
1973 'taxonomy' => 'category',
1974 'terms' => $cat_not_in,
1975 'field' => 'term_id',
1976 'operator' => 'NOT IN',
1977 'include_children' => true
1980 unset( $cat_array, $cat_in, $cat_not_in );
1983 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1984 $q['category__and'] = (array) $q['category__and'];
1985 if ( ! isset( $q['category__in'] ) )
1986 $q['category__in'] = array();
1987 $q['category__in'][] = absint( reset( $q['category__and'] ) );
1988 unset( $q['category__and'] );
1991 if ( ! empty( $q['category__in'] ) ) {
1992 $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1993 $tax_query[] = array(
1994 'taxonomy' => 'category',
1995 'terms' => $q['category__in'],
1996 'field' => 'term_id',
1997 'include_children' => false
2001 if ( ! empty($q['category__not_in']) ) {
2002 $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
2003 $tax_query[] = array(
2004 'taxonomy' => 'category',
2005 'terms' => $q['category__not_in'],
2006 'operator' => 'NOT IN',
2007 'include_children' => false
2011 if ( ! empty($q['category__and']) ) {
2012 $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
2013 $tax_query[] = array(
2014 'taxonomy' => 'category',
2015 'terms' => $q['category__and'],
2016 'field' => 'term_id',
2017 'operator' => 'AND',
2018 'include_children' => false
2022 // If querystring 'tag' is array, implode it.
2023 if ( is_array( $q['tag'] ) ) {
2024 $q['tag'] = implode( ',', $q['tag'] );
2028 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
2029 if ( strpos($q['tag'], ',') !== false ) {
2030 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
2031 foreach ( (array) $tags as $tag ) {
2032 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
2033 $q['tag_slug__in'][] = $tag;
2035 } elseif ( preg_match('/[+\r\n\t ]+/', $q['tag'] ) || ! empty( $q['cat'] ) ) {
2036 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
2037 foreach ( (array) $tags as $tag ) {
2038 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
2039 $q['tag_slug__and'][] = $tag;
2042 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
2043 $q['tag_slug__in'][] = $q['tag'];
2047 if ( !empty($q['tag_id']) ) {
2048 $q['tag_id'] = absint( $q['tag_id'] );
2049 $tax_query[] = array(
2050 'taxonomy' => 'post_tag',
2051 'terms' => $q['tag_id']
2055 if ( !empty($q['tag__in']) ) {
2056 $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
2057 $tax_query[] = array(
2058 'taxonomy' => 'post_tag',
2059 'terms' => $q['tag__in']
2063 if ( !empty($q['tag__not_in']) ) {
2064 $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
2065 $tax_query[] = array(
2066 'taxonomy' => 'post_tag',
2067 'terms' => $q['tag__not_in'],
2068 'operator' => 'NOT IN'
2072 if ( !empty($q['tag__and']) ) {
2073 $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
2074 $tax_query[] = array(
2075 'taxonomy' => 'post_tag',
2076 'terms' => $q['tag__and'],
2081 if ( !empty($q['tag_slug__in']) ) {
2082 $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
2083 $tax_query[] = array(
2084 'taxonomy' => 'post_tag',
2085 'terms' => $q['tag_slug__in'],
2090 if ( !empty($q['tag_slug__and']) ) {
2091 $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
2092 $tax_query[] = array(
2093 'taxonomy' => 'post_tag',
2094 'terms' => $q['tag_slug__and'],
2100 $this->tax_query = new WP_Tax_Query( $tax_query );
2103 * Fires after taxonomy-related query vars have been parsed.
2107 * @param WP_Query $this The WP_Query instance.
2109 do_action( 'parse_tax_query', $this );
2113 * Generate SQL for the WHERE clause based on passed search terms.
2117 * @global wpdb $wpdb WordPress database abstraction object.
2119 * @param array $q Query variables.
2120 * @return string WHERE clause.
2122 protected function parse_search( &$q ) {
2127 // added slashes screw with quote grouping when done early, so done later
2128 $q['s'] = stripslashes( $q['s'] );
2129 if ( empty( $_GET['s'] ) && $this->is_main_query() )
2130 $q['s'] = urldecode( $q['s'] );
2131 // there are no line breaks in <input /> fields
2132 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
2133 $q['search_terms_count'] = 1;
2134 if ( ! empty( $q['sentence'] ) ) {
2135 $q['search_terms'] = array( $q['s'] );
2137 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
2138 $q['search_terms_count'] = count( $matches[0] );
2139 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
2140 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
2141 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
2142 $q['search_terms'] = array( $q['s'] );
2144 $q['search_terms'] = array( $q['s'] );
2148 $n = ! empty( $q['exact'] ) ? '' : '%';
2150 $q['search_orderby_title'] = array();
2151 foreach ( $q['search_terms'] as $term ) {
2152 // Terms prefixed with '-' should be excluded.
2153 $include = '-' !== substr( $term, 0, 1 );
2158 $like_op = 'NOT LIKE';
2160 $term = substr( $term, 1 );
2163 if ( $n && $include ) {
2164 $like = '%' . $wpdb->esc_like( $term ) . '%';
2165 $q['search_orderby_title'][] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like );
2168 $like = $n . $wpdb->esc_like( $term ) . $n;
2169 $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title $like_op %s) $andor_op ($wpdb->posts.post_excerpt $like_op %s) $andor_op ($wpdb->posts.post_content $like_op %s))", $like, $like, $like );
2170 $searchand = ' AND ';
2173 if ( ! empty( $search ) ) {
2174 $search = " AND ({$search}) ";
2175 if ( ! is_user_logged_in() )
2176 $search .= " AND ($wpdb->posts.post_password = '') ";
2183 * Check if the terms are suitable for searching.
2185 * Uses an array of stopwords (terms) that are excluded from the separate
2186 * term matching when searching for posts. The list of English stopwords is
2187 * the approximate search engines list, and is translatable.
2191 * @param array $terms Terms to check.
2192 * @return array Terms that are not stopwords.
2194 protected function parse_search_terms( $terms ) {
2195 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
2198 $stopwords = $this->get_search_stopwords();
2200 foreach ( $terms as $term ) {
2201 // keep before/after spaces when term is for exact match
2202 if ( preg_match( '/^".+"$/', $term ) )
2203 $term = trim( $term, "\"'" );
2205 $term = trim( $term, "\"' " );
2207 // Avoid single A-Z and single dashes.
2208 if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z\-]$/i', $term ) ) )
2211 if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
2221 * Retrieve stopwords used when parsing search terms.
2225 * @return array Stopwords.
2227 protected function get_search_stopwords() {
2228 if ( isset( $this->stopwords ) )
2229 return $this->stopwords;
2231 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
2232 * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
2233 * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
2235 $words = explode( ',', _x( 'about,an,are,as,at,be,by,com,for,from,how,in,is,it,of,on,or,that,the,this,to,was,what,when,where,who,will,with,www',
2236 'Comma-separated list of search stopwords in your language' ) );
2238 $stopwords = array();
2239 foreach ( $words as $word ) {
2240 $word = trim( $word, "\r\n\t " );
2242 $stopwords[] = $word;
2246 * Filters stopwords used when parsing search terms.
2250 * @param array $stopwords Stopwords.
2252 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
2253 return $this->stopwords;
2257 * Generate SQL for the ORDER BY condition based on passed search terms.
2259 * @global wpdb $wpdb WordPress database abstraction object.
2261 * @param array $q Query variables.
2262 * @return string ORDER BY clause.
2264 protected function parse_search_order( &$q ) {
2267 if ( $q['search_terms_count'] > 1 ) {
2268 $num_terms = count( $q['search_orderby_title'] );
2270 // If the search terms contain negative queries, don't bother ordering by sentence matches.
2272 if ( ! preg_match( '/(?:\s|^)\-/', $q['s'] ) ) {
2273 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
2276 $search_orderby = '';
2278 // sentence match in 'post_title'
2280 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_title LIKE %s THEN 1 ", $like );
2283 // sanity limit, sort as sentence when more than 6 terms
2284 // (few searches are longer than 6 terms and most titles are not)
2285 if ( $num_terms < 7 ) {
2286 // all words in title
2287 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
2288 // any word in title, not needed when $num_terms == 1
2289 if ( $num_terms > 1 )
2290 $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
2293 // Sentence match in 'post_content' and 'post_excerpt'.
2295 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_excerpt LIKE %s THEN 4 ", $like );
2296 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 5 ", $like );
2299 if ( $search_orderby ) {
2300 $search_orderby = '(CASE ' . $search_orderby . 'ELSE 6 END)';
2303 // single word or sentence search
2304 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2307 return $search_orderby;
2311 * If the passed orderby value is allowed, convert the alias to a
2312 * properly-prefixed orderby value.
2317 * @global wpdb $wpdb WordPress database abstraction object.
2319 * @param string $orderby Alias for the field to order by.
2320 * @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
2322 protected function parse_orderby( $orderby ) {
2325 // Used to filter values.
2326 $allowed_keys = array(
2327 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2328 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2329 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2332 $primary_meta_key = '';
2333 $primary_meta_query = false;
2334 $meta_clauses = $this->meta_query->get_clauses();
2335 if ( ! empty( $meta_clauses ) ) {
2336 $primary_meta_query = reset( $meta_clauses );
2338 if ( ! empty( $primary_meta_query['key'] ) ) {
2339 $primary_meta_key = $primary_meta_query['key'];
2340 $allowed_keys[] = $primary_meta_key;
2343 $allowed_keys[] = 'meta_value';
2344 $allowed_keys[] = 'meta_value_num';
2345 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
2348 // If RAND() contains a seed value, sanitize and add to allowed keys.
2349 $rand_with_seed = false;
2350 if ( preg_match( '/RAND\(([0-9]+)\)/i', $orderby, $matches ) ) {
2351 $orderby = sprintf( 'RAND(%s)', intval( $matches[1] ) );
2352 $allowed_keys[] = $orderby;
2353 $rand_with_seed = true;
2356 if ( ! in_array( $orderby, $allowed_keys, true ) ) {
2360 switch ( $orderby ) {
2365 case 'post_modified':
2370 case 'comment_count':
2371 $orderby_clause = "$wpdb->posts.{$orderby}";
2374 $orderby_clause = 'RAND()';
2376 case $primary_meta_key:
2378 if ( ! empty( $primary_meta_query['type'] ) ) {
2379 $orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
2381 $orderby_clause = "{$primary_meta_query['alias']}.meta_value";
2384 case 'meta_value_num':
2385 $orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
2388 if ( array_key_exists( $orderby, $meta_clauses ) ) {
2389 // $orderby corresponds to a meta_query clause.
2390 $meta_clause = $meta_clauses[ $orderby ];
2391 $orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
2392 } elseif ( $rand_with_seed ) {
2393 $orderby_clause = $orderby;
2395 // Default: order by post field.
2396 $orderby_clause = "$wpdb->posts.post_" . sanitize_key( $orderby );
2402 return $orderby_clause;
2406 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2411 * @param string $order The 'order' query variable.
2412 * @return string The sanitized 'order' query variable.
2414 protected function parse_order( $order ) {
2415 if ( ! is_string( $order ) || empty( $order ) ) {
2419 if ( 'ASC' === strtoupper( $order ) ) {
2427 * Sets the 404 property and saves whether query is feed.
2432 public function set_404() {
2433 $is_feed = $this->is_feed;
2435 $this->init_query_flags();
2436 $this->is_404 = true;
2438 $this->is_feed = $is_feed;
2442 * Retrieve query variable.
2445 * @since 3.9.0 The `$default` argument was introduced.
2449 * @param string $query_var Query variable key.
2450 * @param mixed $default Optional. Value to return if the query variable is not set. Default empty.
2451 * @return mixed Contents of the query variable.
2453 public function get( $query_var, $default = '' ) {
2454 if ( isset( $this->query_vars[ $query_var ] ) ) {
2455 return $this->query_vars[ $query_var ];
2462 * Set query variable.
2467 * @param string $query_var Query variable key.
2468 * @param mixed $value Query variable value.
2470 public function set($query_var, $value) {
2471 $this->query_vars[$query_var] = $value;
2475 * Retrieve the posts based on query variables.
2477 * There are a few filters and actions that can be used to modify the post
2483 * @global wpdb $wpdb WordPress database abstraction object.
2485 * @return array List of posts.
2487 public function get_posts() {
2490 $this->parse_query();
2493 * Fires after the query variable object is created, but before the actual query is run.
2495 * Note: If using conditional tags, use the method versions within the passed instance
2496 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2497 * like is_main_query() test against the global $wp_query instance, not the passed one.
2501 * @param WP_Query &$this The WP_Query instance (passed by reference).
2503 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2506 $q = &$this->query_vars;
2508 // Fill again in case pre_get_posts unset some vars.
2509 $q = $this->fill_query_vars($q);
2512 $this->meta_query = new WP_Meta_Query();
2513 $this->meta_query->parse_query_vars( $q );
2515 // Set a flag if a pre_get_posts hook changed the query vars.
2516 $hash = md5( serialize( $this->query_vars ) );
2517 if ( $hash != $this->query_vars_hash ) {
2518 $this->query_vars_changed = true;
2519 $this->query_vars_hash = $hash;
2523 // First let's clear some variables
2526 $whichmimetype = '';
2532 $post_status_join = false;
2535 if ( isset( $q['caller_get_posts'] ) ) {
2536 _deprecated_argument( 'WP_Query', '3.1.0', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2537 if ( !isset( $q['ignore_sticky_posts'] ) )
2538 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2541 if ( !isset( $q['ignore_sticky_posts'] ) )
2542 $q['ignore_sticky_posts'] = false;
2544 if ( !isset($q['suppress_filters']) )
2545 $q['suppress_filters'] = false;
2547 if ( !isset($q['cache_results']) ) {
2548 if ( wp_using_ext_object_cache() )
2549 $q['cache_results'] = false;
2551 $q['cache_results'] = true;
2554 if ( !isset($q['update_post_term_cache']) )
2555 $q['update_post_term_cache'] = true;
2557 if ( ! isset( $q['lazy_load_term_meta'] ) ) {
2558 $q['lazy_load_term_meta'] = $q['update_post_term_cache'];
2561 if ( !isset($q['update_post_meta_cache']) )
2562 $q['update_post_meta_cache'] = true;
2564 if ( !isset($q['post_type']) ) {
2565 if ( $this->is_search )
2566 $q['post_type'] = 'any';
2568 $q['post_type'] = '';
2570 $post_type = $q['post_type'];
2571 if ( empty( $q['posts_per_page'] ) ) {
2572 $q['posts_per_page'] = get_option( 'posts_per_page' );
2574 if ( isset($q['showposts']) && $q['showposts'] ) {
2575 $q['showposts'] = (int) $q['showposts'];
2576 $q['posts_per_page'] = $q['showposts'];
2578 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2579 $q['posts_per_page'] = $q['posts_per_archive_page'];
2580 if ( !isset($q['nopaging']) ) {
2581 if ( $q['posts_per_page'] == -1 ) {
2582 $q['nopaging'] = true;
2584 $q['nopaging'] = false;
2588 if ( $this->is_feed ) {
2589 // This overrides posts_per_page.
2590 if ( ! empty( $q['posts_per_rss'] ) ) {
2591 $q['posts_per_page'] = $q['posts_per_rss'];
2593 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2595 $q['nopaging'] = false;
2597 $q['posts_per_page'] = (int) $q['posts_per_page'];
2598 if ( $q['posts_per_page'] < -1 )
2599 $q['posts_per_page'] = abs($q['posts_per_page']);
2600 elseif ( $q['posts_per_page'] == 0 )
2601 $q['posts_per_page'] = 1;
2603 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2604 $q['comments_per_page'] = get_option('comments_per_page');
2606 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2607 $this->is_page = true;
2608 $this->is_home = false;
2609 $q['page_id'] = get_option('page_on_front');
2612 if ( isset($q['page']) ) {
2613 $q['page'] = trim($q['page'], '/');
2614 $q['page'] = absint($q['page']);
2617 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2618 if ( isset($q['no_found_rows']) )
2619 $q['no_found_rows'] = (bool) $q['no_found_rows'];
2621 $q['no_found_rows'] = false;
2623 switch ( $q['fields'] ) {
2625 $fields = "$wpdb->posts.ID";
2628 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2631 $fields = "$wpdb->posts.*";
2634 if ( '' !== $q['menu_order'] )
2635 $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2637 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2639 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2640 if ( strlen($q['m']) > 5 )
2641 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2642 if ( strlen($q['m']) > 7 )
2643 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2644 if ( strlen($q['m']) > 9 )
2645 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2646 if ( strlen($q['m']) > 11 )
2647 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2648 if ( strlen($q['m']) > 13 )
2649 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2652 // Handle the other individual date parameters
2653 $date_parameters = array();
2655 if ( '' !== $q['hour'] )
2656 $date_parameters['hour'] = $q['hour'];
2658 if ( '' !== $q['minute'] )
2659 $date_parameters['minute'] = $q['minute'];
2661 if ( '' !== $q['second'] )
2662 $date_parameters['second'] = $q['second'];
2665 $date_parameters['year'] = $q['year'];
2667 if ( $q['monthnum'] )
2668 $date_parameters['monthnum'] = $q['monthnum'];
2671 $date_parameters['week'] = $q['w'];
2674 $date_parameters['day'] = $q['day'];
2676 if ( $date_parameters ) {
2677 $date_query = new WP_Date_Query( array( $date_parameters ) );
2678 $where .= $date_query->get_sql();
2680 unset( $date_parameters, $date_query );
2682 // Handle complex date queries
2683 if ( ! empty( $q['date_query'] ) ) {
2684 $this->date_query = new WP_Date_Query( $q['date_query'] );
2685 $where .= $this->date_query->get_sql();
2689 // If we've got a post_type AND it's not "any" post_type.
2690 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2691 foreach ( (array)$q['post_type'] as $_post_type ) {
2692 $ptype_obj = get_post_type_object($_post_type);
2693 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2696 if ( ! $ptype_obj->hierarchical ) {
2697 // Non-hierarchical post types can directly use 'name'.
2698 $q['name'] = $q[ $ptype_obj->query_var ];
2700 // Hierarchical post types will operate through 'pagename'.
2701 $q['pagename'] = $q[ $ptype_obj->query_var ];
2705 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2711 if ( '' !== $q['title'] ) {
2712 $where .= $wpdb->prepare( " AND $wpdb->posts.post_title = %s", stripslashes( $q['title'] ) );
2715 // Parameters related to 'post_name'.
2716 if ( '' != $q['name'] ) {
2717 $q['name'] = sanitize_title_for_query( $q['name'] );
2718 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2719 } elseif ( '' != $q['pagename'] ) {
2720 if ( isset($this->queried_object_id) ) {
2721 $reqpage = $this->queried_object_id;
2723 if ( 'page' != $q['post_type'] ) {
2724 foreach ( (array)$q['post_type'] as $_post_type ) {
2725 $ptype_obj = get_post_type_object($_post_type);
2726 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2729 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2735 $reqpage = get_page_by_path($q['pagename']);
2737 if ( !empty($reqpage) )
2738 $reqpage = $reqpage->ID;
2743 $page_for_posts = get_option('page_for_posts');
2744 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2745 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2746 $q['name'] = $q['pagename'];
2747 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2748 $reqpage_obj = get_post( $reqpage );
2749 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2750 $this->is_attachment = true;
2751 $post_type = $q['post_type'] = 'attachment';
2752 $this->is_page = true;
2753 $q['attachment_id'] = $reqpage;
2756 } elseif ( '' != $q['attachment'] ) {
2757 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2758 $q['name'] = $q['attachment'];
2759 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2760 } elseif ( is_array( $q['post_name__in'] ) && ! empty( $q['post_name__in'] ) ) {
2761 $q['post_name__in'] = array_map( 'sanitize_title_for_query', $q['post_name__in'] );
2762 $post_name__in = "'" . implode( "','", $q['post_name__in'] ) . "'";
2763 $where .= " AND $wpdb->posts.post_name IN ($post_name__in)";
2766 // If an attachment is requested by number, let it supersede any post number.
2767 if ( $q['attachment_id'] )
2768 $q['p'] = absint($q['attachment_id']);
2770 // If a post number is specified, load that post
2772 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2773 } elseif ( $q['post__in'] ) {
2774 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2775 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2776 } elseif ( $q['post__not_in'] ) {
2777 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
2778 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2781 if ( is_numeric( $q['post_parent'] ) ) {
2782 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2783 } elseif ( $q['post_parent__in'] ) {
2784 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2785 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2786 } elseif ( $q['post_parent__not_in'] ) {
2787 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
2788 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2791 if ( $q['page_id'] ) {
2792 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2793 $q['p'] = $q['page_id'];
2794 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2798 // If a search pattern is specified, load the posts that match.
2799 if ( strlen( $q['s'] ) ) {
2800 $search = $this->parse_search( $q );
2803 if ( ! $q['suppress_filters'] ) {
2805 * Filters the search SQL that is used in the WHERE clause of WP_Query.
2809 * @param string $search Search SQL for WHERE clause.
2810 * @param WP_Query $this The current WP_Query object.
2812 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2816 if ( !$this->is_singular ) {
2817 $this->parse_tax_query( $q );
2819 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2821 $join .= $clauses['join'];
2822 $where .= $clauses['where'];
2825 if ( $this->is_tax ) {
2826 if ( empty($post_type) ) {
2827 // Do a fully inclusive search for currently registered post types of queried taxonomies
2828 $post_type = array();
2829 $taxonomies = array_keys( $this->tax_query->queried_terms );
2830 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2831 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2832 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2837 elseif ( count( $post_type ) == 1 )
2838 $post_type = $post_type[0];
2840 $post_status_join = true;
2841 } elseif ( in_array('attachment', (array) $post_type) ) {
2842 $post_status_join = true;
2847 * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2848 * 'category_name' vars are set for backward compatibility.
2850 if ( ! empty( $this->tax_query->queried_terms ) ) {
2853 * Set 'taxonomy', 'term', and 'term_id' to the
2854 * first taxonomy other than 'post_tag' or 'category'.
2856 if ( ! isset( $q['taxonomy'] ) ) {
2857 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2858 if ( empty( $queried_items['terms'][0] ) ) {
2862 if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2863 $q['taxonomy'] = $queried_taxonomy;
2865 if ( 'slug' === $queried_items['field'] ) {
2866 $q['term'] = $queried_items['terms'][0];
2868 $q['term_id'] = $queried_items['terms'][0];
2871 // Take the first one we find.
2877 // 'cat', 'category_name', 'tag_id'
2878 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2879 if ( empty( $queried_items['terms'][0] ) ) {
2883 if ( 'category' === $queried_taxonomy ) {
2884 $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2886 $this->set( 'cat', $the_cat->term_id );
2887 $this->set( 'category_name', $the_cat->slug );
2892 if ( 'post_tag' === $queried_taxonomy ) {
2893 $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2895 $this->set( 'tag_id', $the_tag->term_id );
2902 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2903 $groupby = "{$wpdb->posts}.ID";
2906 // Author/user stuff
2908 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2909 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2910 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2911 foreach ( $authors as $author ) {
2912 $key = $author > 0 ? 'author__in' : 'author__not_in';
2913 $q[$key][] = abs( $author );
2915 $q['author'] = implode( ',', $authors );
2918 if ( ! empty( $q['author__not_in'] ) ) {
2919 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2920 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2921 } elseif ( ! empty( $q['author__in'] ) ) {
2922 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2923 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2926 // Author stuff for nice URLs
2928 if ( '' != $q['author_name'] ) {
2929 if ( strpos($q['author_name'], '/') !== false ) {
2930 $q['author_name'] = explode('/', $q['author_name']);
2931 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2932 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2934 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2937 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2938 $q['author'] = get_user_by('slug', $q['author_name']);
2940 $q['author'] = $q['author']->ID;
2941 $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2944 // MIME-Type stuff for attachment browsing
2946 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2947 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2949 $where .= $search . $whichauthor . $whichmimetype;
2951 if ( ! empty( $this->meta_query->queries ) ) {
2952 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
2953 $join .= $clauses['join'];
2954 $where .= $clauses['where'];
2957 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2958 if ( ! isset( $q['order'] ) ) {
2959 $q['order'] = $rand ? '' : 'DESC';
2961 $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2965 if ( empty( $q['orderby'] ) ) {
2967 * Boolean false or empty array blanks out ORDER BY,
2968 * while leaving the value unset or otherwise empty sets the default.
2970 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2973 $orderby = "$wpdb->posts.post_date " . $q['order'];
2975 } elseif ( 'none' == $q['orderby'] ) {
2977 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2978 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2979 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2980 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2981 } elseif ( $q['orderby'] == 'post_name__in' && ! empty( $post_name__in ) ) {
2982 $orderby = "FIELD( {$wpdb->posts}.post_name, $post_name__in )";
2984 $orderby_array = array();
2985 if ( is_array( $q['orderby'] ) ) {
2986 foreach ( $q['orderby'] as $_orderby => $order ) {
2987 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2988 $parsed = $this->parse_orderby( $orderby );
2994 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2996 $orderby = implode( ', ', $orderby_array );
2999 $q['orderby'] = urldecode( $q['orderby'] );
3000 $q['orderby'] = addslashes_gpc( $q['orderby'] );
3002 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
3003 $parsed = $this->parse_orderby( $orderby );
3004 // Only allow certain values for safety.
3009 $orderby_array[] = $parsed;
3011 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
3013 if ( empty( $orderby ) ) {
3014 $orderby = "$wpdb->posts.post_date " . $q['order'];
3015 } elseif ( ! empty( $q['order'] ) ) {
3016 $orderby .= " {$q['order']}";
3021 // Order search results by relevance only when another "orderby" is not specified in the query.
3022 if ( ! empty( $q['s'] ) ) {
3023 $search_orderby = '';
3024 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
3025 $search_orderby = $this->parse_search_order( $q );
3027 if ( ! $q['suppress_filters'] ) {
3029 * Filters the ORDER BY used when ordering search results.
3033 * @param string $search_orderby The ORDER BY clause.
3034 * @param WP_Query $this The current WP_Query instance.
3036 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
3039 if ( $search_orderby )
3040 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
3043 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
3044 $post_type_cap = 'multiple_post_type';
3046 if ( is_array( $post_type ) )
3047 $post_type = reset( $post_type );
3048 $post_type_object = get_post_type_object( $post_type );
3049 if ( empty( $post_type_object ) )
3050 $post_type_cap = $post_type;
3053 if ( isset( $q['post_password'] ) ) {
3054 $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
3055 if ( empty( $q['perm'] ) ) {
3056 $q['perm'] = 'readable';
3058 } elseif ( isset( $q['has_password'] ) ) {
3059 $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
3062 if ( ! empty( $q['comment_status'] ) ) {
3063 $where .= $wpdb->prepare( " AND $wpdb->posts.comment_status = %s ", $q['comment_status'] );
3066 if ( ! empty( $q['ping_status'] ) ) {
3067 $where .= $wpdb->prepare( " AND $wpdb->posts.ping_status = %s ", $q['ping_status'] );
3070 if ( 'any' == $post_type ) {
3071 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
3072 if ( empty( $in_search_post_types ) ) {
3073 $where .= ' AND 1=0 ';
3075 $where .= " AND {$wpdb->posts}.post_type IN ('" . join( "', '", array_map( 'esc_sql', $in_search_post_types ) ) . "')";
3077 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
3078 $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", esc_sql( $post_type ) ) . "')";
3079 } elseif ( ! empty( $post_type ) ) {
3080 $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_type = %s", $post_type );
3081 $post_type_object = get_post_type_object ( $post_type );
3082 } elseif ( $this->is_attachment ) {
3083 $where .= " AND $wpdb->posts.post_type = 'attachment'";
3084 $post_type_object = get_post_type_object ( 'attachment' );
3085 } elseif ( $this->is_page ) {
3086 $where .= " AND $wpdb->posts.post_type = 'page'";
3087 $post_type_object = get_post_type_object ( 'page' );
3089 $where .= " AND $wpdb->posts.post_type = 'post'";
3090 $post_type_object = get_post_type_object ( 'post' );
3093 $edit_cap = 'edit_post';
3094 $read_cap = 'read_post';
3096 if ( ! empty( $post_type_object ) ) {
3097 $edit_others_cap = $post_type_object->cap->edit_others_posts;
3098 $read_private_cap = $post_type_object->cap->read_private_posts;
3100 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
3101 $read_private_cap = 'read_private_' . $post_type_cap . 's';
3104 $user_id = get_current_user_id();
3106 $q_status = array();
3107 if ( ! empty( $q['post_status'] ) ) {
3108 $statuswheres = array();
3109 $q_status = $q['post_status'];
3110 if ( ! is_array( $q_status ) )
3111 $q_status = explode(',', $q_status);
3112 $r_status = array();
3113 $p_status = array();
3114 $e_status = array();
3115 if ( in_array( 'any', $q_status ) ) {
3116 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
3117 if ( ! in_array( $status, $q_status ) ) {
3118 $e_status[] = "$wpdb->posts.post_status <> '$status'";
3122 foreach ( get_post_stati() as $status ) {
3123 if ( in_array( $status, $q_status ) ) {
3124 if ( 'private' == $status )
3125 $p_status[] = "$wpdb->posts.post_status = '$status'";
3127 $r_status[] = "$wpdb->posts.post_status = '$status'";
3132 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
3133 $r_status = array_merge($r_status, $p_status);
3137 if ( !empty($e_status) ) {
3138 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
3140 if ( !empty($r_status) ) {
3141 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
3142 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
3144 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
3146 if ( !empty($p_status) ) {
3147 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
3148 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
3150 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
3152 if ( $post_status_join ) {
3153 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
3154 foreach ( $statuswheres as $index => $statuswhere )
3155 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
3157 $where_status = implode( ' OR ', $statuswheres );
3158 if ( ! empty( $where_status ) ) {
3159 $where .= " AND ($where_status)";
3161 } elseif ( !$this->is_singular ) {
3162 $where .= " AND ($wpdb->posts.post_status = 'publish'";
3164 // Add public states.
3165 $public_states = get_post_stati( array('public' => true) );
3166 foreach ( (array) $public_states as $state ) {
3167 if ( 'publish' == $state ) // Publish is hard-coded above.
3169 $where .= " OR $wpdb->posts.post_status = '$state'";
3172 if ( $this->is_admin ) {
3173 // Add protected states that should show in the admin all list.
3174 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3175 foreach ( (array) $admin_all_states as $state )
3176 $where .= " OR $wpdb->posts.post_status = '$state'";
3179 if ( is_user_logged_in() ) {
3180 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3181 $private_states = get_post_stati( array('private' => true) );
3182 foreach ( (array) $private_states as $state )
3183 $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'";
3190 * Apply filters on where and join prior to paging so that any
3191 * manipulations to them are reflected in the paging by day queries.
3193 if ( !$q['suppress_filters'] ) {
3195 * Filters the WHERE clause of the query.
3199 * @param string $where The WHERE clause of the query.
3200 * @param WP_Query &$this The WP_Query instance (passed by reference).
3202 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3205 * Filters the JOIN clause of the query.
3209 * @param string $where The JOIN clause of the query.
3210 * @param WP_Query &$this The WP_Query instance (passed by reference).
3212 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3216 if ( empty($q['nopaging']) && !$this->is_singular ) {
3217 $page = absint($q['paged']);
3221 // If 'offset' is provided, it takes precedence over 'paged'.
3222 if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
3223 $q['offset'] = absint( $q['offset'] );
3224 $pgstrt = $q['offset'] . ', ';
3226 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3228 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3232 if ( $this->is_comment_feed && ! $this->is_singular ) {
3233 if ( $this->is_archive || $this->is_search ) {
3234 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3235 $cwhere = "WHERE comment_approved = '1' $where";
3236 $cgroupby = "$wpdb->comments.comment_id";
3237 } else { // Other non singular e.g. front
3238 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3239 $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' && post_type = 'attachment' ) ) AND comment_approved = '1'";
3243 if ( !$q['suppress_filters'] ) {
3245 * Filters the JOIN clause of the comments feed query before sending.
3249 * @param string $cjoin The JOIN clause of the query.
3250 * @param WP_Query &$this The WP_Query instance (passed by reference).
3252 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3255 * Filters the WHERE clause of the comments feed query before sending.
3259 * @param string $cwhere The WHERE clause of the query.
3260 * @param WP_Query &$this The WP_Query instance (passed by reference).
3262 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3265 * Filters the GROUP BY clause of the comments feed query before sending.
3269 * @param string $cgroupby The GROUP BY clause of the query.
3270 * @param WP_Query &$this The WP_Query instance (passed by reference).
3272 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3275 * Filters the ORDER BY clause of the comments feed query before sending.
3279 * @param string $corderby The ORDER BY clause of the query.
3280 * @param WP_Query &$this The WP_Query instance (passed by reference).
3282 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3285 * Filters the LIMIT clause of the comments feed query before sending.
3289 * @param string $climits The JOIN clause of the query.
3290 * @param WP_Query &$this The WP_Query instance (passed by reference).
3292 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3294 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3295 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3297 $comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3298 // Convert to WP_Comment
3299 $this->comments = array_map( 'get_comment', $comments );
3300 $this->comment_count = count($this->comments);
3302 $post_ids = array();
3304 foreach ( $this->comments as $comment )
3305 $post_ids[] = (int) $comment->comment_post_ID;
3307 $post_ids = join(',', $post_ids);
3310 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3315 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3318 * Apply post-paging filters on where and join. Only plugins that
3319 * manipulate paging queries should use these hooks.
3321 if ( !$q['suppress_filters'] ) {
3323 * Filters the WHERE clause of the query.
3325 * Specifically for manipulating paging queries.
3329 * @param string $where The WHERE clause of the query.
3330 * @param WP_Query &$this The WP_Query instance (passed by reference).
3332 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3335 * Filters the GROUP BY clause of the query.
3339 * @param string $groupby The GROUP BY clause of the query.
3340 * @param WP_Query &$this The WP_Query instance (passed by reference).
3342 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3345 * Filters the JOIN clause of the query.
3347 * Specifically for manipulating paging queries.
3351 * @param string $join The JOIN clause of the query.
3352 * @param WP_Query &$this The WP_Query instance (passed by reference).
3354 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3357 * Filters the ORDER BY clause of the query.
3361 * @param string $orderby The ORDER BY clause of the query.
3362 * @param WP_Query &$this The WP_Query instance (passed by reference).
3364 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3367 * Filters the DISTINCT clause of the query.
3371 * @param string $distinct The DISTINCT clause of the query.
3372 * @param WP_Query &$this The WP_Query instance (passed by reference).
3374 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3377 * Filters the LIMIT clause of the query.
3381 * @param string $limits The LIMIT clause of the query.
3382 * @param WP_Query &$this The WP_Query instance (passed by reference).
3384 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3387 * Filters the SELECT clause of the query.
3391 * @param string $fields The SELECT clause of the query.
3392 * @param WP_Query &$this The WP_Query instance (passed by reference).
3394 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3397 * Filters all query clauses at once, for convenience.
3399 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3400 * fields (SELECT), and LIMITS clauses.
3404 * @param array $clauses The list of clauses for the query.
3405 * @param WP_Query &$this The WP_Query instance (passed by reference).
3407 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3409 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3410 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3411 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3412 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3413 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3414 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3415 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3419 * Fires to announce the query's current selection parameters.
3421 * For use by caching plugins.
3425 * @param string $selection The assembled selection query.
3427 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3430 * Filters again for the benefit of caching plugins.
3431 * Regular plugins should use the hooks above.
3433 if ( !$q['suppress_filters'] ) {
3435 * Filters the WHERE clause of the query.
3437 * For use by caching plugins.
3441 * @param string $where The WHERE clause of the query.
3442 * @param WP_Query &$this The WP_Query instance (passed by reference).
3444 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3447 * Filters the GROUP BY clause of the query.
3449 * For use by caching plugins.
3453 * @param string $groupby The GROUP BY clause of the query.
3454 * @param WP_Query &$this The WP_Query instance (passed by reference).
3456 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3459 * Filters the JOIN clause of the query.
3461 * For use by caching plugins.
3465 * @param string $join The JOIN clause of the query.
3466 * @param WP_Query &$this The WP_Query instance (passed by reference).
3468 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3471 * Filters the ORDER BY clause of the query.
3473 * For use by caching plugins.
3477 * @param string $orderby The ORDER BY clause of the query.
3478 * @param WP_Query &$this The WP_Query instance (passed by reference).
3480 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3483 * Filters the DISTINCT clause of the query.
3485 * For use by caching plugins.
3489 * @param string $distinct The DISTINCT clause of the query.
3490 * @param WP_Query &$this The WP_Query instance (passed by reference).
3492 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3495 * Filters the SELECT clause of the query.
3497 * For use by caching plugins.
3501 * @param string $fields The SELECT clause of the query.
3502 * @param WP_Query &$this The WP_Query instance (passed by reference).
3504 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3507 * Filters the LIMIT clause of the query.
3509 * For use by caching plugins.
3513 * @param string $limits The LIMIT clause of the query.
3514 * @param WP_Query &$this The WP_Query instance (passed by reference).
3516 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3519 * Filters all query clauses at once, for convenience.
3521 * For use by caching plugins.
3523 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3524 * fields (SELECT), and LIMITS clauses.
3528 * @param array $pieces The pieces of the query.
3529 * @param WP_Query &$this The WP_Query instance (passed by reference).
3531 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3533 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3534 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3535 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3536 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3537 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3538 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3539 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3542 if ( ! empty($groupby) )
3543 $groupby = 'GROUP BY ' . $groupby;
3544 if ( !empty( $orderby ) )
3545 $orderby = 'ORDER BY ' . $orderby;
3548 if ( !$q['no_found_rows'] && !empty($limits) )
3549 $found_rows = 'SQL_CALC_FOUND_ROWS';
3551 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3553 if ( !$q['suppress_filters'] ) {
3555 * Filters the completed SQL query before sending.
3559 * @param string $request The complete SQL query.
3560 * @param WP_Query &$this The WP_Query instance (passed by reference).
3562 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3566 * Filters the posts array before the query takes place.
3568 * Return a non-null value to bypass WordPress's default post queries.
3570 * Filtering functions that require pagination information are encouraged to set
3571 * the `found_posts` and `max_num_pages` properties of the WP_Query object,
3572 * passed to the filter by reference. If WP_Query does not perform a database
3573 * query, it will not have enough information to generate these values itself.
3577 * @param array|null $posts Return an array of post data to short-circuit WP's query,
3578 * or null to allow WP to run its normal queries.
3579 * @param WP_Query $this The WP_Query instance, passed by reference.
3581 $this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );
3583 if ( 'ids' == $q['fields'] ) {
3584 if ( null === $this->posts ) {
3585 $this->posts = $wpdb->get_col( $this->request );
3588 $this->posts = array_map( 'intval', $this->posts );
3589 $this->post_count = count( $this->posts );
3590 $this->set_found_posts( $q, $limits );
3592 return $this->posts;
3595 if ( 'id=>parent' == $q['fields'] ) {
3596 if ( null === $this->posts ) {
3597 $this->posts = $wpdb->get_results( $this->request );
3600 $this->post_count = count( $this->posts );
3601 $this->set_found_posts( $q, $limits );
3604 foreach ( $this->posts as $key => $post ) {
3605 $this->posts[ $key ]->ID = (int) $post->ID;
3606 $this->posts[ $key ]->post_parent = (int) $post->post_parent;
3608 $r[ (int) $post->ID ] = (int) $post->post_parent;
3614 if ( null === $this->posts ) {
3615 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3618 * Filters whether to split the query.
3620 * Splitting the query will cause it to fetch just the IDs of the found posts
3621 * (and then individually fetch each post by ID), rather than fetching every
3622 * complete row at once. One massive result vs. many small results.
3626 * @param bool $split_the_query Whether or not to split the query.
3627 * @param WP_Query $this The WP_Query instance.
3629 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3631 if ( $split_the_query ) {
3632 // First get the IDs and then fill in the objects
3634 $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3637 * Filters the Post IDs SQL request before sending.
3641 * @param string $request The post ID request.
3642 * @param WP_Query $this The WP_Query instance.
3644 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3646 $ids = $wpdb->get_col( $this->request );
3649 $this->posts = $ids;
3650 $this->set_found_posts( $q, $limits );
3651 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3653 $this->posts = array();
3656 $this->posts = $wpdb->get_results( $this->request );
3657 $this->set_found_posts( $q, $limits );
3661 // Convert to WP_Post objects.
3662 if ( $this->posts ) {
3663 $this->posts = array_map( 'get_post', $this->posts );
3666 if ( ! $q['suppress_filters'] ) {
3668 * Filters the raw post results array, prior to status checks.
3672 * @param array $posts The post results array.
3673 * @param WP_Query &$this The WP_Query instance (passed by reference).
3675 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3678 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3679 /** This filter is documented in wp-includes/query.php */
3680 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3682 /** This filter is documented in wp-includes/query.php */
3683 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3685 /** This filter is documented in wp-includes/query.php */
3686 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3687 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3689 /** This filter is documented in wp-includes/query.php */
3690 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3691 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3693 /** This filter is documented in wp-includes/query.php */
3694 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3696 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3697 $comments = $wpdb->get_results($comments_request);
3698 // Convert to WP_Comment
3699 $this->comments = array_map( 'get_comment', $comments );
3700 $this->comment_count = count($this->comments);
3703 // Check post status to determine if post should be displayed.
3704 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3705 $status = get_post_status($this->posts[0]);
3706 if ( 'attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent ) {
3707 $this->is_page = false;
3708 $this->is_single = true;
3709 $this->is_attachment = true;
3711 $post_status_obj = get_post_status_object($status);
3713 // If the post_status was specifically requested, let it pass through.
3714 if ( !$post_status_obj->public && ! in_array( $status, $q_status ) ) {
3716 if ( ! is_user_logged_in() ) {
3717 // User must be logged in to view unpublished posts.
3718 $this->posts = array();
3720 if ( $post_status_obj->protected ) {
3721 // User must have edit permissions on the draft to preview.
3722 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3723 $this->posts = array();
3725 $this->is_preview = true;
3726 if ( 'future' != $status )
3727 $this->posts[0]->post_date = current_time('mysql');
3729 } elseif ( $post_status_obj->private ) {
3730 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3731 $this->posts = array();
3733 $this->posts = array();
3738 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3740 * Filters the single post for preview mode.
3744 * @param WP_Post $post_preview The Post object.
3745 * @param WP_Query &$this The WP_Query instance (passed by reference).
3747 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3751 // Put sticky posts at the top of the posts array
3752 $sticky_posts = get_option('sticky_posts');
3753 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3754 $num_posts = count($this->posts);
3756 // Loop over posts and relocate stickies to the front.
3757 for ( $i = 0; $i < $num_posts; $i++ ) {
3758 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3759 $sticky_post = $this->posts[$i];
3760 // Remove sticky from current position
3761 array_splice($this->posts, $i, 1);
3762 // Move to front, after other stickies
3763 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3764 // Increment the sticky offset. The next sticky will be placed at this offset.
3766 // Remove post from sticky posts array
3767 $offset = array_search($sticky_post->ID, $sticky_posts);
3768 unset( $sticky_posts[$offset] );
3772 // If any posts have been excluded specifically, Ignore those that are sticky.
3773 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3774 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3776 // Fetch sticky posts that weren't in the query results
3777 if ( !empty($sticky_posts) ) {
3778 $stickies = get_posts( array(
3779 'post__in' => $sticky_posts,
3780 'post_type' => $post_type,
3781 'post_status' => 'publish',
3785 foreach ( $stickies as $sticky_post ) {
3786 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3792 // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
3793 if ( ! empty( $this->comments ) ) {
3794 wp_queue_comments_for_comment_meta_lazyload( $this->comments );
3797 if ( ! $q['suppress_filters'] ) {
3799 * Filters the array of retrieved posts after they've been fetched and
3800 * internally processed.
3804 * @param array $posts The array of retrieved posts.
3805 * @param WP_Query &$this The WP_Query instance (passed by reference).
3807 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3810 // Ensure that any posts added/modified via one of the filters above are
3811 // of the type WP_Post and are filtered.
3812 if ( $this->posts ) {
3813 $this->post_count = count( $this->posts );
3815 $this->posts = array_map( 'get_post', $this->posts );
3817 if ( $q['cache_results'] )
3818 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3820 $this->post = reset( $this->posts );
3822 $this->post_count = 0;
3823 $this->posts = array();
3826 if ( $q['lazy_load_term_meta'] ) {
3827 wp_queue_posts_for_term_meta_lazyload( $this->posts );
3830 return $this->posts;
3834 * Set up the amount of found posts and the number of pages (if limit clause was used)
3835 * for the current query.
3840 * @global wpdb $wpdb WordPress database abstraction object.
3842 * @param array $q Query variables.
3843 * @param string $limits LIMIT clauses of the query.
3845 private function set_found_posts( $q, $limits ) {
3848 // Bail if posts is an empty array. Continue if posts is an empty string,
3849 // null, or false to accommodate caching plugins that fill posts later.
3850 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3853 if ( ! empty( $limits ) ) {
3855 * Filters the query to run for retrieving the found posts.
3859 * @param string $found_posts The query to run to find the found posts.
3860 * @param WP_Query &$this The WP_Query instance (passed by reference).
3862 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3864 $this->found_posts = count( $this->posts );
3868 * Filters the number of found posts for the query.
3872 * @param int $found_posts The number of posts found.
3873 * @param WP_Query &$this The WP_Query instance (passed by reference).
3875 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3877 if ( ! empty( $limits ) )
3878 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3882 * Set up the next post and iterate current post index.
3887 * @return WP_Post Next post.
3889 public function next_post() {
3891 $this->current_post++;
3893 $this->post = $this->posts[$this->current_post];
3898 * Sets up the current post.
3900 * Retrieves the next post, sets up the post, sets the 'in the loop'
3906 * @global WP_Post $post
3908 public function the_post() {
3910 $this->in_the_loop = true;
3912 if ( $this->current_post == -1 ) // loop has just started
3914 * Fires once the loop is started.
3918 * @param WP_Query &$this The WP_Query instance (passed by reference).
3920 do_action_ref_array( 'loop_start', array( &$this ) );
3922 $post = $this->next_post();
3923 $this->setup_postdata( $post );
3927 * Determines whether there are more posts available in the loop.
3929 * Calls the {@see 'loop_end'} action when the loop is complete.
3934 * @return bool True if posts are available, false if end of loop.
3936 public function have_posts() {
3937 if ( $this->current_post + 1 < $this->post_count ) {
3939 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3941 * Fires once the loop has ended.
3945 * @param WP_Query &$this The WP_Query instance (passed by reference).
3947 do_action_ref_array( 'loop_end', array( &$this ) );
3948 // Do some cleaning up after the loop
3949 $this->rewind_posts();
3952 $this->in_the_loop = false;
3957 * Rewind the posts and reset post index.
3962 public function rewind_posts() {
3963 $this->current_post = -1;
3964 if ( $this->post_count > 0 ) {
3965 $this->post = $this->posts[0];
3970 * Iterate current comment index and return WP_Comment object.
3975 * @return WP_Comment Comment object.
3977 public function next_comment() {
3978 $this->current_comment++;
3980 $this->comment = $this->comments[$this->current_comment];
3981 return $this->comment;
3985 * Sets up the current comment.
3989 * @global WP_Comment $comment Current comment.
3991 public function the_comment() {
3994 $comment = $this->next_comment();
3996 if ( $this->current_comment == 0 ) {
3998 * Fires once the comment loop is started.
4002 do_action( 'comment_loop_start' );
4007 * Whether there are more comments available.
4009 * Automatically rewinds comments when finished.
4014 * @return bool True, if more comments. False, if no more posts.
4016 public function have_comments() {
4017 if ( $this->current_comment + 1 < $this->comment_count ) {
4019 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
4020 $this->rewind_comments();
4027 * Rewind the comments, resets the comment index and comment to first.
4032 public function rewind_comments() {
4033 $this->current_comment = -1;
4034 if ( $this->comment_count > 0 ) {
4035 $this->comment = $this->comments[0];
4040 * Sets up the WordPress query by parsing query string.
4045 * @param string $query URL query string.
4046 * @return array List of posts.
4048 public function query( $query ) {
4050 $this->query = $this->query_vars = wp_parse_args( $query );
4051 return $this->get_posts();
4055 * Retrieve queried object.
4057 * If queried object is not set, then the queried object will be set from
4058 * the category, tag, taxonomy, posts page, single post, page, or author
4059 * query variable. After it is set up, it will be returned.
4066 public function get_queried_object() {
4067 if ( isset($this->queried_object) )
4068 return $this->queried_object;
4070 $this->queried_object = null;
4071 $this->queried_object_id = null;
4073 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
4074 if ( $this->is_category ) {
4075 if ( $this->get( 'cat' ) ) {
4076 $term = get_term( $this->get( 'cat' ), 'category' );
4077 } elseif ( $this->get( 'category_name' ) ) {
4078 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
4080 } elseif ( $this->is_tag ) {
4081 if ( $this->get( 'tag_id' ) ) {
4082 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
4083 } elseif ( $this->get( 'tag' ) ) {
4084 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
4087 // For other tax queries, grab the first term from the first clause.
4088 $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' );
4090 if ( ! empty( $tax_query_in_and ) ) {
4091 $queried_taxonomies = array_keys( $tax_query_in_and );
4092 $matched_taxonomy = reset( $queried_taxonomies );
4093 $query = $tax_query_in_and[ $matched_taxonomy ];
4095 if ( $query['terms'] ) {
4096 if ( 'term_id' == $query['field'] ) {
4097 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
4099 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
4105 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
4106 $this->queried_object = $term;
4107 $this->queried_object_id = (int) $term->term_id;
4109 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
4110 _make_cat_compat( $this->queried_object );
4112 } elseif ( $this->is_post_type_archive ) {
4113 $post_type = $this->get( 'post_type' );
4114 if ( is_array( $post_type ) )
4115 $post_type = reset( $post_type );
4116 $this->queried_object = get_post_type_object( $post_type );
4117 } elseif ( $this->is_posts_page ) {
4118 $page_for_posts = get_option('page_for_posts');
4119 $this->queried_object = get_post( $page_for_posts );
4120 $this->queried_object_id = (int) $this->queried_object->ID;
4121 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
4122 $this->queried_object = $this->post;
4123 $this->queried_object_id = (int) $this->post->ID;
4124 } elseif ( $this->is_author ) {
4125 $this->queried_object_id = (int) $this->get('author');
4126 $this->queried_object = get_userdata( $this->queried_object_id );
4129 return $this->queried_object;
4133 * Retrieve ID of the current queried object.
4140 public function get_queried_object_id() {
4141 $this->get_queried_object();
4143 if ( isset($this->queried_object_id) ) {
4144 return $this->queried_object_id;
4153 * Sets up the WordPress query, if parameter is not empty.
4158 * @param string|array $query URL query string or array of vars.
4160 public function __construct($query = '') {
4161 if ( ! empty($query) ) {
4162 $this->query($query);
4167 * Make private properties readable for backward compatibility.
4172 * @param string $name Property to get.
4173 * @return mixed Property.
4175 public function __get( $name ) {
4176 if ( in_array( $name, $this->compat_fields ) ) {
4177 return $this->$name;
4182 * Make private properties checkable for backward compatibility.
4187 * @param string $name Property to check if set.
4188 * @return bool Whether the property is set.
4190 public function __isset( $name ) {
4191 if ( in_array( $name, $this->compat_fields ) ) {
4192 return isset( $this->$name );
4197 * Make private/protected methods readable for backward compatibility.
4202 * @param callable $name Method to call.
4203 * @param array $arguments Arguments to pass when calling.
4204 * @return mixed|false Return value of the callback, false otherwise.
4206 public function __call( $name, $arguments ) {
4207 if ( in_array( $name, $this->compat_methods ) ) {
4208 return call_user_func_array( array( $this, $name ), $arguments );
4214 * Is the query for an existing archive page?
4216 * Month, Year, Category, Author, Post Type archive...
4222 public function is_archive() {
4223 return (bool) $this->is_archive;
4227 * Is the query for an existing post type archive page?
4231 * @param mixed $post_types Optional. Post type or array of posts types to check against.
4234 public function is_post_type_archive( $post_types = '' ) {
4235 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4236 return (bool) $this->is_post_type_archive;
4238 $post_type = $this->get( 'post_type' );
4239 if ( is_array( $post_type ) )
4240 $post_type = reset( $post_type );
4241 $post_type_object = get_post_type_object( $post_type );
4243 return in_array( $post_type_object->name, (array) $post_types );
4247 * Is the query for an existing attachment page?
4251 * @param mixed $attachment Attachment ID, title, slug, or array of such.
4254 public function is_attachment( $attachment = '' ) {
4255 if ( ! $this->is_attachment ) {
4259 if ( empty( $attachment ) ) {
4263 $attachment = array_map( 'strval', (array) $attachment );
4265 $post_obj = $this->get_queried_object();
4267 if ( in_array( (string) $post_obj->ID, $attachment ) ) {
4269 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4271 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4278 * Is the query for an existing author archive page?
4280 * If the $author parameter is specified, this function will additionally
4281 * check if the query is for one of the authors specified.
4285 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4288 public function is_author( $author = '' ) {
4289 if ( !$this->is_author )
4292 if ( empty($author) )
4295 $author_obj = $this->get_queried_object();
4297 $author = array_map( 'strval', (array) $author );
4299 if ( in_array( (string) $author_obj->ID, $author ) )
4301 elseif ( in_array( $author_obj->nickname, $author ) )
4303 elseif ( in_array( $author_obj->user_nicename, $author ) )
4310 * Is the query for an existing category archive page?
4312 * If the $category parameter is specified, this function will additionally
4313 * check if the query is for one of the categories specified.
4317 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4320 public function is_category( $category = '' ) {
4321 if ( !$this->is_category )
4324 if ( empty($category) )
4327 $cat_obj = $this->get_queried_object();
4329 $category = array_map( 'strval', (array) $category );
4331 if ( in_array( (string) $cat_obj->term_id, $category ) )
4333 elseif ( in_array( $cat_obj->name, $category ) )
4335 elseif ( in_array( $cat_obj->slug, $category ) )
4342 * Is the query for an existing tag archive page?
4344 * If the $tag parameter is specified, this function will additionally
4345 * check if the query is for one of the tags specified.
4349 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4352 public function is_tag( $tag = '' ) {
4353 if ( ! $this->is_tag )
4356 if ( empty( $tag ) )
4359 $tag_obj = $this->get_queried_object();
4361 $tag = array_map( 'strval', (array) $tag );
4363 if ( in_array( (string) $tag_obj->term_id, $tag ) )
4365 elseif ( in_array( $tag_obj->name, $tag ) )
4367 elseif ( in_array( $tag_obj->slug, $tag ) )
4374 * Is the query for an existing custom taxonomy archive page?
4376 * If the $taxonomy parameter is specified, this function will additionally
4377 * check if the query is for that specific $taxonomy.
4379 * If the $term parameter is specified in addition to the $taxonomy parameter,
4380 * this function will additionally check if the query is for one of the terms
4385 * @global array $wp_taxonomies
4387 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4388 * @param mixed $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4389 * @return bool True for custom taxonomy archive pages, false for built-in taxonomies (category and tag archives).
4391 public function is_tax( $taxonomy = '', $term = '' ) {
4392 global $wp_taxonomies;
4394 if ( !$this->is_tax )
4397 if ( empty( $taxonomy ) )
4400 $queried_object = $this->get_queried_object();
4401 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4402 $term_array = (array) $term;
4404 // Check that the taxonomy matches.
4405 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4408 // Only a Taxonomy provided.
4409 if ( empty( $term ) )
4412 return isset( $queried_object->term_id ) &&
4413 count( array_intersect(
4414 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4420 * Whether the current URL is within the comments popup window.
4427 public function is_comments_popup() {
4428 _deprecated_function( __FUNCTION__, '4.5.0' );
4434 * Is the query for an existing date archive?
4440 public function is_date() {
4441 return (bool) $this->is_date;
4445 * Is the query for an existing day archive?
4451 public function is_day() {
4452 return (bool) $this->is_day;
4456 * Is the query for a feed?
4460 * @param string|array $feeds Optional feed types to check.
4463 public function is_feed( $feeds = '' ) {
4464 if ( empty( $feeds ) || ! $this->is_feed )
4465 return (bool) $this->is_feed;
4466 $qv = $this->get( 'feed' );
4467 if ( 'feed' == $qv )
4468 $qv = get_default_feed();
4469 return in_array( $qv, (array) $feeds );
4473 * Is the query for a comments feed?
4479 public function is_comment_feed() {
4480 return (bool) $this->is_comment_feed;
4484 * Is the query for the front page of the site?
4486 * This is for what is displayed at your site's main URL.
4488 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4490 * If you set a static page for the front page of your site, this function will return
4491 * true when viewing that page.
4493 * Otherwise the same as @see WP_Query::is_home()
4497 * @return bool True, if front of site.
4499 public function is_front_page() {
4501 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4503 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4510 * Is the query for the blog homepage?
4512 * This is the page which shows the time based blog content of your site.
4514 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4516 * If you set a static page for the front page of your site, this function will return
4517 * true only on the page you set as the "Posts page".
4519 * @see WP_Query::is_front_page()
4523 * @return bool True if blog view homepage.
4525 public function is_home() {
4526 return (bool) $this->is_home;
4530 * Is the query for an existing month archive?
4536 public function is_month() {
4537 return (bool) $this->is_month;
4541 * Is the query for an existing single page?
4543 * If the $page parameter is specified, this function will additionally
4544 * check if the query is for one of the pages specified.
4546 * @see WP_Query::is_single()
4547 * @see WP_Query::is_singular()
4551 * @param int|string|array $page Optional. Page ID, title, slug, path, or array of such. Default empty.
4552 * @return bool Whether the query is for an existing single page.
4554 public function is_page( $page = '' ) {
4555 if ( !$this->is_page )
4558 if ( empty( $page ) )
4561 $page_obj = $this->get_queried_object();
4563 $page = array_map( 'strval', (array) $page );
4565 if ( in_array( (string) $page_obj->ID, $page ) ) {
4567 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4569 } elseif ( in_array( $page_obj->post_name, $page ) ) {
4572 foreach ( $page as $pagepath ) {
4573 if ( ! strpos( $pagepath, '/' ) ) {
4576 $pagepath_obj = get_page_by_path( $pagepath );
4578 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4588 * Is the query for paged result and not for the first page?
4594 public function is_paged() {
4595 return (bool) $this->is_paged;
4599 * Is the query for a post or page preview?
4605 public function is_preview() {
4606 return (bool) $this->is_preview;
4610 * Is the query for the robots file?
4616 public function is_robots() {
4617 return (bool) $this->is_robots;
4621 * Is the query for a search?
4627 public function is_search() {
4628 return (bool) $this->is_search;
4632 * Is the query for an existing single post?
4634 * Works for any post type, except attachments and pages
4636 * If the $post parameter is specified, this function will additionally
4637 * check if the query is for one of the Posts specified.
4639 * @see WP_Query::is_page()
4640 * @see WP_Query::is_singular()
4644 * @param int|string|array $post Optional. Post ID, title, slug, path, or array of such. Default empty.
4645 * @return bool Whether the query is for an existing single post.
4647 public function is_single( $post = '' ) {
4648 if ( !$this->is_single )
4654 $post_obj = $this->get_queried_object();
4656 $post = array_map( 'strval', (array) $post );
4658 if ( in_array( (string) $post_obj->ID, $post ) ) {
4660 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4662 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4665 foreach ( $post as $postpath ) {
4666 if ( ! strpos( $postpath, '/' ) ) {
4669 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4671 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4680 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4682 * If the $post_types parameter is specified, this function will additionally
4683 * check if the query is for one of the Posts Types specified.
4685 * @see WP_Query::is_page()
4686 * @see WP_Query::is_single()
4690 * @param string|array $post_types Optional. Post type or array of post types. Default empty.
4691 * @return bool Whether the query is for an existing single post of any of the given post types.
4693 public function is_singular( $post_types = '' ) {
4694 if ( empty( $post_types ) || !$this->is_singular )
4695 return (bool) $this->is_singular;
4697 $post_obj = $this->get_queried_object();
4699 return in_array( $post_obj->post_type, (array) $post_types );
4703 * Is the query for a specific time?
4709 public function is_time() {
4710 return (bool) $this->is_time;
4714 * Is the query for a trackback endpoint call?
4720 public function is_trackback() {
4721 return (bool) $this->is_trackback;
4725 * Is the query for an existing year archive?
4731 public function is_year() {
4732 return (bool) $this->is_year;
4736 * Is the query a 404 (returns no results)?
4742 public function is_404() {
4743 return (bool) $this->is_404;
4747 * Is the query for an embedded post?
4753 public function is_embed() {
4754 return (bool) $this->is_embed;
4758 * Is the query the main query?
4762 * @global WP_Query $wp_query Global WP_Query instance.
4766 public function is_main_query() {
4767 global $wp_the_query;
4768 return $wp_the_query === $this;
4772 * Set up global post data.
4775 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
4778 * @global WP_User $authordata
4779 * @global string|int|bool $currentday
4780 * @global string|int|bool $currentmonth
4782 * @global array $pages
4783 * @global int $multipage
4785 * @global int $numpages
4787 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
4788 * @return true True when finished.
4790 public function setup_postdata( $post ) {
4791 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4793 if ( ! ( $post instanceof WP_Post ) ) {
4794 $post = get_post( $post );
4801 $id = (int) $post->ID;
4803 $authordata = get_userdata($post->post_author);
4805 $currentday = mysql2date('d.m.y', $post->post_date, false);
4806 $currentmonth = mysql2date('m', $post->post_date, false);
4809 $page = $this->get( 'page' );
4814 * Force full post content when viewing the permalink for the $post,
4815 * or when on an RSS feed. Otherwise respect the 'more' tag.
4817 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4819 } elseif ( $this->is_feed() ) {
4825 $content = $post->post_content;
4826 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4827 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4828 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4829 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4831 // Ignore nextpage at the beginning of the content.
4832 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4833 $content = substr( $content, 15 );
4835 $pages = explode('<!--nextpage-->', $content);
4837 $pages = array( $post->post_content );
4841 * Filters the "pages" derived from splitting the post content.
4843 * "Pages" are determined by splitting the post content based on the presence
4844 * of `<!-- nextpage -->` tags.
4848 * @param array $pages Array of "pages" derived from the post content.
4849 * of `<!-- nextpage -->` tags..
4850 * @param WP_Post $post Current post object.
4852 $pages = apply_filters( 'content_pagination', $pages, $post );
4854 $numpages = count( $pages );
4856 if ( $numpages > 1 ) {
4866 * Fires once the post data has been setup.
4869 * @since 4.1.0 Introduced `$this` parameter.
4871 * @param WP_Post &$post The Post object (passed by reference).
4872 * @param WP_Query &$this The current Query object (passed by reference).
4874 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4879 * After looping through a nested query, this function
4880 * restores the $post global to the current post in this query.
4884 * @global WP_Post $post
4886 public function reset_postdata() {
4887 if ( ! empty( $this->post ) ) {
4888 $GLOBALS['post'] = $this->post;
4889 $this->setup_postdata( $this->post );
4894 * Lazyload term meta for posts in the loop.
4897 * @deprecated 4.5.0 See wp_queue_posts_for_term_meta_lazyload().
4899 * @param mixed $check
4900 * @param int $term_id
4903 public function lazyload_term_meta( $check, $term_id ) {
4904 _deprecated_function( __METHOD__, '4.5.0' );
4909 * Lazyload comment meta for comments in the loop.
4912 * @deprecated 4.5.0 See wp_queue_comments_for_comment_meta_lazyload().
4914 * @param mixed $check
4915 * @param int $comment_id
4918 public function lazyload_comment_meta( $check, $comment_id ) {
4919 _deprecated_function( __METHOD__, '4.5.0' );
4925 * Redirect old slugs to the correct permalink.
4927 * Attempts to find the current slug from the past slugs.
4931 * @global WP_Query $wp_query Global WP_Query instance.
4932 * @global wpdb $wpdb WordPress database abstraction object.
4934 function wp_old_slug_redirect() {
4937 if ( is_404() && '' !== $wp_query->query_vars['name'] ) :
4940 // Guess the current post_type based on the query vars.
4941 if ( get_query_var( 'post_type' ) ) {
4942 $post_type = get_query_var( 'post_type' );
4943 } elseif ( get_query_var( 'attachment' ) ) {
4944 $post_type = 'attachment';
4945 } elseif ( ! empty( $wp_query->query_vars['pagename'] ) ) {
4946 $post_type = 'page';
4948 $post_type = 'post';
4951 if ( is_array( $post_type ) ) {
4952 if ( count( $post_type ) > 1 )
4954 $post_type = reset( $post_type );
4957 // Do not attempt redirect for hierarchical post types
4958 if ( is_post_type_hierarchical( $post_type ) )
4961 $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']);
4963 // if year, monthnum, or day have been specified, make our query more precise
4964 // just in case there are multiple identical _wp_old_slug values
4965 if ( '' != $wp_query->query_vars['year'] )
4966 $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
4967 if ( '' != $wp_query->query_vars['monthnum'] )
4968 $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
4969 if ( '' != $wp_query->query_vars['day'] )
4970 $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
4972 $id = (int) $wpdb->get_var($query);
4977 $link = get_permalink( $id );
4979 if ( isset( $GLOBALS['wp_query']->query_vars['paged'] ) && $GLOBALS['wp_query']->query_vars['paged'] > 1 ) {
4980 $link = user_trailingslashit( trailingslashit( $link ) . 'page/' . $GLOBALS['wp_query']->query_vars['paged'] );
4981 } elseif( is_embed() ) {
4982 $link = user_trailingslashit( trailingslashit( $link ) . 'embed' );
4986 * Filters the old slug redirect URL.
4990 * @param string $link The redirect URL.
4992 $link = apply_filters( 'old_slug_redirect_url', $link );
4998 wp_redirect( $link, 301 ); // Permanent redirect
5004 * Set up global post data.
5007 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
5009 * @global WP_Query $wp_query Global WP_Query instance.
5011 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
5012 * @return bool True when finished.
5014 function setup_postdata( $post ) {
5017 if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
5018 return $wp_query->setup_postdata( $post );