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("', '", $in_search_post_types ) . "')";
3076 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
3077 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
3078 } elseif ( ! empty( $post_type ) ) {
3079 $where .= " AND $wpdb->posts.post_type = '$post_type'";
3080 $post_type_object = get_post_type_object ( $post_type );
3081 } elseif ( $this->is_attachment ) {
3082 $where .= " AND $wpdb->posts.post_type = 'attachment'";
3083 $post_type_object = get_post_type_object ( 'attachment' );
3084 } elseif ( $this->is_page ) {
3085 $where .= " AND $wpdb->posts.post_type = 'page'";
3086 $post_type_object = get_post_type_object ( 'page' );
3088 $where .= " AND $wpdb->posts.post_type = 'post'";
3089 $post_type_object = get_post_type_object ( 'post' );
3092 $edit_cap = 'edit_post';
3093 $read_cap = 'read_post';
3095 if ( ! empty( $post_type_object ) ) {
3096 $edit_others_cap = $post_type_object->cap->edit_others_posts;
3097 $read_private_cap = $post_type_object->cap->read_private_posts;
3099 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
3100 $read_private_cap = 'read_private_' . $post_type_cap . 's';
3103 $user_id = get_current_user_id();
3105 $q_status = array();
3106 if ( ! empty( $q['post_status'] ) ) {
3107 $statuswheres = array();
3108 $q_status = $q['post_status'];
3109 if ( ! is_array( $q_status ) )
3110 $q_status = explode(',', $q_status);
3111 $r_status = array();
3112 $p_status = array();
3113 $e_status = array();
3114 if ( in_array( 'any', $q_status ) ) {
3115 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
3116 if ( ! in_array( $status, $q_status ) ) {
3117 $e_status[] = "$wpdb->posts.post_status <> '$status'";
3121 foreach ( get_post_stati() as $status ) {
3122 if ( in_array( $status, $q_status ) ) {
3123 if ( 'private' == $status )
3124 $p_status[] = "$wpdb->posts.post_status = '$status'";
3126 $r_status[] = "$wpdb->posts.post_status = '$status'";
3131 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
3132 $r_status = array_merge($r_status, $p_status);
3136 if ( !empty($e_status) ) {
3137 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
3139 if ( !empty($r_status) ) {
3140 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
3141 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
3143 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
3145 if ( !empty($p_status) ) {
3146 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
3147 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
3149 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
3151 if ( $post_status_join ) {
3152 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
3153 foreach ( $statuswheres as $index => $statuswhere )
3154 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
3156 $where_status = implode( ' OR ', $statuswheres );
3157 if ( ! empty( $where_status ) ) {
3158 $where .= " AND ($where_status)";
3160 } elseif ( !$this->is_singular ) {
3161 $where .= " AND ($wpdb->posts.post_status = 'publish'";
3163 // Add public states.
3164 $public_states = get_post_stati( array('public' => true) );
3165 foreach ( (array) $public_states as $state ) {
3166 if ( 'publish' == $state ) // Publish is hard-coded above.
3168 $where .= " OR $wpdb->posts.post_status = '$state'";
3171 if ( $this->is_admin ) {
3172 // Add protected states that should show in the admin all list.
3173 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3174 foreach ( (array) $admin_all_states as $state )
3175 $where .= " OR $wpdb->posts.post_status = '$state'";
3178 if ( is_user_logged_in() ) {
3179 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3180 $private_states = get_post_stati( array('private' => true) );
3181 foreach ( (array) $private_states as $state )
3182 $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'";
3189 * Apply filters on where and join prior to paging so that any
3190 * manipulations to them are reflected in the paging by day queries.
3192 if ( !$q['suppress_filters'] ) {
3194 * Filters the WHERE clause of the query.
3198 * @param string $where The WHERE clause of the query.
3199 * @param WP_Query &$this The WP_Query instance (passed by reference).
3201 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3204 * Filters the JOIN clause of the query.
3208 * @param string $where The JOIN clause of the query.
3209 * @param WP_Query &$this The WP_Query instance (passed by reference).
3211 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3215 if ( empty($q['nopaging']) && !$this->is_singular ) {
3216 $page = absint($q['paged']);
3220 // If 'offset' is provided, it takes precedence over 'paged'.
3221 if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
3222 $q['offset'] = absint( $q['offset'] );
3223 $pgstrt = $q['offset'] . ', ';
3225 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3227 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3231 if ( $this->is_comment_feed && ! $this->is_singular ) {
3232 if ( $this->is_archive || $this->is_search ) {
3233 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3234 $cwhere = "WHERE comment_approved = '1' $where";
3235 $cgroupby = "$wpdb->comments.comment_id";
3236 } else { // Other non singular e.g. front
3237 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3238 $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' && post_type = 'attachment' ) ) AND comment_approved = '1'";
3242 if ( !$q['suppress_filters'] ) {
3244 * Filters the JOIN clause of the comments feed query before sending.
3248 * @param string $cjoin The JOIN clause of the query.
3249 * @param WP_Query &$this The WP_Query instance (passed by reference).
3251 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3254 * Filters the WHERE clause of the comments feed query before sending.
3258 * @param string $cwhere The WHERE clause of the query.
3259 * @param WP_Query &$this The WP_Query instance (passed by reference).
3261 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3264 * Filters the GROUP BY clause of the comments feed query before sending.
3268 * @param string $cgroupby The GROUP BY clause of the query.
3269 * @param WP_Query &$this The WP_Query instance (passed by reference).
3271 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3274 * Filters the ORDER BY clause of the comments feed query before sending.
3278 * @param string $corderby The ORDER BY clause of the query.
3279 * @param WP_Query &$this The WP_Query instance (passed by reference).
3281 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3284 * Filters the LIMIT clause of the comments feed query before sending.
3288 * @param string $climits The JOIN clause of the query.
3289 * @param WP_Query &$this The WP_Query instance (passed by reference).
3291 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3293 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3294 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3296 $comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3297 // Convert to WP_Comment
3298 $this->comments = array_map( 'get_comment', $comments );
3299 $this->comment_count = count($this->comments);
3301 $post_ids = array();
3303 foreach ( $this->comments as $comment )
3304 $post_ids[] = (int) $comment->comment_post_ID;
3306 $post_ids = join(',', $post_ids);
3309 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3314 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3317 * Apply post-paging filters on where and join. Only plugins that
3318 * manipulate paging queries should use these hooks.
3320 if ( !$q['suppress_filters'] ) {
3322 * Filters the WHERE clause of the query.
3324 * Specifically for manipulating paging queries.
3328 * @param string $where The WHERE clause of the query.
3329 * @param WP_Query &$this The WP_Query instance (passed by reference).
3331 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3334 * Filters the GROUP BY clause of the query.
3338 * @param string $groupby The GROUP BY clause of the query.
3339 * @param WP_Query &$this The WP_Query instance (passed by reference).
3341 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3344 * Filters the JOIN clause of the query.
3346 * Specifically for manipulating paging queries.
3350 * @param string $join The JOIN clause of the query.
3351 * @param WP_Query &$this The WP_Query instance (passed by reference).
3353 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3356 * Filters the ORDER BY clause of the query.
3360 * @param string $orderby The ORDER BY clause of the query.
3361 * @param WP_Query &$this The WP_Query instance (passed by reference).
3363 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3366 * Filters the DISTINCT clause of the query.
3370 * @param string $distinct The DISTINCT clause of the query.
3371 * @param WP_Query &$this The WP_Query instance (passed by reference).
3373 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3376 * Filters the LIMIT clause of the query.
3380 * @param string $limits The LIMIT clause of the query.
3381 * @param WP_Query &$this The WP_Query instance (passed by reference).
3383 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3386 * Filters the SELECT clause of the query.
3390 * @param string $fields The SELECT clause of the query.
3391 * @param WP_Query &$this The WP_Query instance (passed by reference).
3393 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3396 * Filters all query clauses at once, for convenience.
3398 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3399 * fields (SELECT), and LIMITS clauses.
3403 * @param array $clauses The list of clauses for the query.
3404 * @param WP_Query &$this The WP_Query instance (passed by reference).
3406 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3408 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3409 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3410 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3411 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3412 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3413 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3414 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3418 * Fires to announce the query's current selection parameters.
3420 * For use by caching plugins.
3424 * @param string $selection The assembled selection query.
3426 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3429 * Filters again for the benefit of caching plugins.
3430 * Regular plugins should use the hooks above.
3432 if ( !$q['suppress_filters'] ) {
3434 * Filters the WHERE clause of the query.
3436 * For use by caching plugins.
3440 * @param string $where The WHERE clause of the query.
3441 * @param WP_Query &$this The WP_Query instance (passed by reference).
3443 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3446 * Filters the GROUP BY clause of the query.
3448 * For use by caching plugins.
3452 * @param string $groupby The GROUP BY clause of the query.
3453 * @param WP_Query &$this The WP_Query instance (passed by reference).
3455 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3458 * Filters the JOIN clause of the query.
3460 * For use by caching plugins.
3464 * @param string $join The JOIN clause of the query.
3465 * @param WP_Query &$this The WP_Query instance (passed by reference).
3467 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3470 * Filters the ORDER BY clause of the query.
3472 * For use by caching plugins.
3476 * @param string $orderby The ORDER BY clause of the query.
3477 * @param WP_Query &$this The WP_Query instance (passed by reference).
3479 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3482 * Filters the DISTINCT clause of the query.
3484 * For use by caching plugins.
3488 * @param string $distinct The DISTINCT clause of the query.
3489 * @param WP_Query &$this The WP_Query instance (passed by reference).
3491 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3494 * Filters the SELECT clause of the query.
3496 * For use by caching plugins.
3500 * @param string $fields The SELECT clause of the query.
3501 * @param WP_Query &$this The WP_Query instance (passed by reference).
3503 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3506 * Filters the LIMIT clause of the query.
3508 * For use by caching plugins.
3512 * @param string $limits The LIMIT clause of the query.
3513 * @param WP_Query &$this The WP_Query instance (passed by reference).
3515 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3518 * Filters all query clauses at once, for convenience.
3520 * For use by caching plugins.
3522 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3523 * fields (SELECT), and LIMITS clauses.
3527 * @param array $pieces The pieces of the query.
3528 * @param WP_Query &$this The WP_Query instance (passed by reference).
3530 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3532 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3533 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3534 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3535 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3536 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3537 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3538 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3541 if ( ! empty($groupby) )
3542 $groupby = 'GROUP BY ' . $groupby;
3543 if ( !empty( $orderby ) )
3544 $orderby = 'ORDER BY ' . $orderby;
3547 if ( !$q['no_found_rows'] && !empty($limits) )
3548 $found_rows = 'SQL_CALC_FOUND_ROWS';
3550 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3552 if ( !$q['suppress_filters'] ) {
3554 * Filters the completed SQL query before sending.
3558 * @param string $request The complete SQL query.
3559 * @param WP_Query &$this The WP_Query instance (passed by reference).
3561 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3565 * Filters the posts array before the query takes place.
3567 * Return a non-null value to bypass WordPress's default post queries.
3569 * Filtering functions that require pagination information are encouraged to set
3570 * the `found_posts` and `max_num_pages` properties of the WP_Query object,
3571 * passed to the filter by reference. If WP_Query does not perform a database
3572 * query, it will not have enough information to generate these values itself.
3576 * @param array|null $posts Return an array of post data to short-circuit WP's query,
3577 * or null to allow WP to run its normal queries.
3578 * @param WP_Query $this The WP_Query instance, passed by reference.
3580 $this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );
3582 if ( 'ids' == $q['fields'] ) {
3583 if ( null === $this->posts ) {
3584 $this->posts = $wpdb->get_col( $this->request );
3587 $this->posts = array_map( 'intval', $this->posts );
3588 $this->post_count = count( $this->posts );
3589 $this->set_found_posts( $q, $limits );
3591 return $this->posts;
3594 if ( 'id=>parent' == $q['fields'] ) {
3595 if ( null === $this->posts ) {
3596 $this->posts = $wpdb->get_results( $this->request );
3599 $this->post_count = count( $this->posts );
3600 $this->set_found_posts( $q, $limits );
3603 foreach ( $this->posts as $key => $post ) {
3604 $this->posts[ $key ]->ID = (int) $post->ID;
3605 $this->posts[ $key ]->post_parent = (int) $post->post_parent;
3607 $r[ (int) $post->ID ] = (int) $post->post_parent;
3613 if ( null === $this->posts ) {
3614 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3617 * Filters whether to split the query.
3619 * Splitting the query will cause it to fetch just the IDs of the found posts
3620 * (and then individually fetch each post by ID), rather than fetching every
3621 * complete row at once. One massive result vs. many small results.
3625 * @param bool $split_the_query Whether or not to split the query.
3626 * @param WP_Query $this The WP_Query instance.
3628 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3630 if ( $split_the_query ) {
3631 // First get the IDs and then fill in the objects
3633 $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3636 * Filters the Post IDs SQL request before sending.
3640 * @param string $request The post ID request.
3641 * @param WP_Query $this The WP_Query instance.
3643 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3645 $ids = $wpdb->get_col( $this->request );
3648 $this->posts = $ids;
3649 $this->set_found_posts( $q, $limits );
3650 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3652 $this->posts = array();
3655 $this->posts = $wpdb->get_results( $this->request );
3656 $this->set_found_posts( $q, $limits );
3660 // Convert to WP_Post objects.
3661 if ( $this->posts ) {
3662 $this->posts = array_map( 'get_post', $this->posts );
3665 if ( ! $q['suppress_filters'] ) {
3667 * Filters the raw post results array, prior to status checks.
3671 * @param array $posts The post results array.
3672 * @param WP_Query &$this The WP_Query instance (passed by reference).
3674 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3677 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3678 /** This filter is documented in wp-includes/query.php */
3679 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3681 /** This filter is documented in wp-includes/query.php */
3682 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3684 /** This filter is documented in wp-includes/query.php */
3685 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3686 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3688 /** This filter is documented in wp-includes/query.php */
3689 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3690 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3692 /** This filter is documented in wp-includes/query.php */
3693 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3695 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3696 $comments = $wpdb->get_results($comments_request);
3697 // Convert to WP_Comment
3698 $this->comments = array_map( 'get_comment', $comments );
3699 $this->comment_count = count($this->comments);
3702 // Check post status to determine if post should be displayed.
3703 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3704 $status = get_post_status($this->posts[0]);
3705 if ( 'attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent ) {
3706 $this->is_page = false;
3707 $this->is_single = true;
3708 $this->is_attachment = true;
3710 $post_status_obj = get_post_status_object($status);
3712 // If the post_status was specifically requested, let it pass through.
3713 if ( !$post_status_obj->public && ! in_array( $status, $q_status ) ) {
3715 if ( ! is_user_logged_in() ) {
3716 // User must be logged in to view unpublished posts.
3717 $this->posts = array();
3719 if ( $post_status_obj->protected ) {
3720 // User must have edit permissions on the draft to preview.
3721 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3722 $this->posts = array();
3724 $this->is_preview = true;
3725 if ( 'future' != $status )
3726 $this->posts[0]->post_date = current_time('mysql');
3728 } elseif ( $post_status_obj->private ) {
3729 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3730 $this->posts = array();
3732 $this->posts = array();
3737 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3739 * Filters the single post for preview mode.
3743 * @param WP_Post $post_preview The Post object.
3744 * @param WP_Query &$this The WP_Query instance (passed by reference).
3746 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3750 // Put sticky posts at the top of the posts array
3751 $sticky_posts = get_option('sticky_posts');
3752 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3753 $num_posts = count($this->posts);
3755 // Loop over posts and relocate stickies to the front.
3756 for ( $i = 0; $i < $num_posts; $i++ ) {
3757 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3758 $sticky_post = $this->posts[$i];
3759 // Remove sticky from current position
3760 array_splice($this->posts, $i, 1);
3761 // Move to front, after other stickies
3762 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3763 // Increment the sticky offset. The next sticky will be placed at this offset.
3765 // Remove post from sticky posts array
3766 $offset = array_search($sticky_post->ID, $sticky_posts);
3767 unset( $sticky_posts[$offset] );
3771 // If any posts have been excluded specifically, Ignore those that are sticky.
3772 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3773 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3775 // Fetch sticky posts that weren't in the query results
3776 if ( !empty($sticky_posts) ) {
3777 $stickies = get_posts( array(
3778 'post__in' => $sticky_posts,
3779 'post_type' => $post_type,
3780 'post_status' => 'publish',
3784 foreach ( $stickies as $sticky_post ) {
3785 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3791 // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
3792 if ( ! empty( $this->comments ) ) {
3793 wp_queue_comments_for_comment_meta_lazyload( $this->comments );
3796 if ( ! $q['suppress_filters'] ) {
3798 * Filters the array of retrieved posts after they've been fetched and
3799 * internally processed.
3803 * @param array $posts The array of retrieved posts.
3804 * @param WP_Query &$this The WP_Query instance (passed by reference).
3806 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3809 // Ensure that any posts added/modified via one of the filters above are
3810 // of the type WP_Post and are filtered.
3811 if ( $this->posts ) {
3812 $this->post_count = count( $this->posts );
3814 $this->posts = array_map( 'get_post', $this->posts );
3816 if ( $q['cache_results'] )
3817 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3819 $this->post = reset( $this->posts );
3821 $this->post_count = 0;
3822 $this->posts = array();
3825 if ( $q['lazy_load_term_meta'] ) {
3826 wp_queue_posts_for_term_meta_lazyload( $this->posts );
3829 return $this->posts;
3833 * Set up the amount of found posts and the number of pages (if limit clause was used)
3834 * for the current query.
3839 * @global wpdb $wpdb WordPress database abstraction object.
3841 * @param array $q Query variables.
3842 * @param string $limits LIMIT clauses of the query.
3844 private function set_found_posts( $q, $limits ) {
3847 // Bail if posts is an empty array. Continue if posts is an empty string,
3848 // null, or false to accommodate caching plugins that fill posts later.
3849 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3852 if ( ! empty( $limits ) ) {
3854 * Filters the query to run for retrieving the found posts.
3858 * @param string $found_posts The query to run to find the found posts.
3859 * @param WP_Query &$this The WP_Query instance (passed by reference).
3861 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3863 $this->found_posts = count( $this->posts );
3867 * Filters the number of found posts for the query.
3871 * @param int $found_posts The number of posts found.
3872 * @param WP_Query &$this The WP_Query instance (passed by reference).
3874 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3876 if ( ! empty( $limits ) )
3877 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3881 * Set up the next post and iterate current post index.
3886 * @return WP_Post Next post.
3888 public function next_post() {
3890 $this->current_post++;
3892 $this->post = $this->posts[$this->current_post];
3897 * Sets up the current post.
3899 * Retrieves the next post, sets up the post, sets the 'in the loop'
3905 * @global WP_Post $post
3907 public function the_post() {
3909 $this->in_the_loop = true;
3911 if ( $this->current_post == -1 ) // loop has just started
3913 * Fires once the loop is started.
3917 * @param WP_Query &$this The WP_Query instance (passed by reference).
3919 do_action_ref_array( 'loop_start', array( &$this ) );
3921 $post = $this->next_post();
3922 $this->setup_postdata( $post );
3926 * Determines whether there are more posts available in the loop.
3928 * Calls the {@see 'loop_end'} action when the loop is complete.
3933 * @return bool True if posts are available, false if end of loop.
3935 public function have_posts() {
3936 if ( $this->current_post + 1 < $this->post_count ) {
3938 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3940 * Fires once the loop has ended.
3944 * @param WP_Query &$this The WP_Query instance (passed by reference).
3946 do_action_ref_array( 'loop_end', array( &$this ) );
3947 // Do some cleaning up after the loop
3948 $this->rewind_posts();
3951 $this->in_the_loop = false;
3956 * Rewind the posts and reset post index.
3961 public function rewind_posts() {
3962 $this->current_post = -1;
3963 if ( $this->post_count > 0 ) {
3964 $this->post = $this->posts[0];
3969 * Iterate current comment index and return WP_Comment object.
3974 * @return WP_Comment Comment object.
3976 public function next_comment() {
3977 $this->current_comment++;
3979 $this->comment = $this->comments[$this->current_comment];
3980 return $this->comment;
3984 * Sets up the current comment.
3988 * @global WP_Comment $comment Current comment.
3990 public function the_comment() {
3993 $comment = $this->next_comment();
3995 if ( $this->current_comment == 0 ) {
3997 * Fires once the comment loop is started.
4001 do_action( 'comment_loop_start' );
4006 * Whether there are more comments available.
4008 * Automatically rewinds comments when finished.
4013 * @return bool True, if more comments. False, if no more posts.
4015 public function have_comments() {
4016 if ( $this->current_comment + 1 < $this->comment_count ) {
4018 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
4019 $this->rewind_comments();
4026 * Rewind the comments, resets the comment index and comment to first.
4031 public function rewind_comments() {
4032 $this->current_comment = -1;
4033 if ( $this->comment_count > 0 ) {
4034 $this->comment = $this->comments[0];
4039 * Sets up the WordPress query by parsing query string.
4044 * @param string $query URL query string.
4045 * @return array List of posts.
4047 public function query( $query ) {
4049 $this->query = $this->query_vars = wp_parse_args( $query );
4050 return $this->get_posts();
4054 * Retrieve queried object.
4056 * If queried object is not set, then the queried object will be set from
4057 * the category, tag, taxonomy, posts page, single post, page, or author
4058 * query variable. After it is set up, it will be returned.
4065 public function get_queried_object() {
4066 if ( isset($this->queried_object) )
4067 return $this->queried_object;
4069 $this->queried_object = null;
4070 $this->queried_object_id = null;
4072 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
4073 if ( $this->is_category ) {
4074 if ( $this->get( 'cat' ) ) {
4075 $term = get_term( $this->get( 'cat' ), 'category' );
4076 } elseif ( $this->get( 'category_name' ) ) {
4077 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
4079 } elseif ( $this->is_tag ) {
4080 if ( $this->get( 'tag_id' ) ) {
4081 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
4082 } elseif ( $this->get( 'tag' ) ) {
4083 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
4086 // For other tax queries, grab the first term from the first clause.
4087 $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' );
4089 if ( ! empty( $tax_query_in_and ) ) {
4090 $queried_taxonomies = array_keys( $tax_query_in_and );
4091 $matched_taxonomy = reset( $queried_taxonomies );
4092 $query = $tax_query_in_and[ $matched_taxonomy ];
4094 if ( $query['terms'] ) {
4095 if ( 'term_id' == $query['field'] ) {
4096 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
4098 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
4104 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
4105 $this->queried_object = $term;
4106 $this->queried_object_id = (int) $term->term_id;
4108 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
4109 _make_cat_compat( $this->queried_object );
4111 } elseif ( $this->is_post_type_archive ) {
4112 $post_type = $this->get( 'post_type' );
4113 if ( is_array( $post_type ) )
4114 $post_type = reset( $post_type );
4115 $this->queried_object = get_post_type_object( $post_type );
4116 } elseif ( $this->is_posts_page ) {
4117 $page_for_posts = get_option('page_for_posts');
4118 $this->queried_object = get_post( $page_for_posts );
4119 $this->queried_object_id = (int) $this->queried_object->ID;
4120 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
4121 $this->queried_object = $this->post;
4122 $this->queried_object_id = (int) $this->post->ID;
4123 } elseif ( $this->is_author ) {
4124 $this->queried_object_id = (int) $this->get('author');
4125 $this->queried_object = get_userdata( $this->queried_object_id );
4128 return $this->queried_object;
4132 * Retrieve ID of the current queried object.
4139 public function get_queried_object_id() {
4140 $this->get_queried_object();
4142 if ( isset($this->queried_object_id) ) {
4143 return $this->queried_object_id;
4152 * Sets up the WordPress query, if parameter is not empty.
4157 * @param string|array $query URL query string or array of vars.
4159 public function __construct($query = '') {
4160 if ( ! empty($query) ) {
4161 $this->query($query);
4166 * Make private properties readable for backward compatibility.
4171 * @param string $name Property to get.
4172 * @return mixed Property.
4174 public function __get( $name ) {
4175 if ( in_array( $name, $this->compat_fields ) ) {
4176 return $this->$name;
4181 * Make private properties checkable for backward compatibility.
4186 * @param string $name Property to check if set.
4187 * @return bool Whether the property is set.
4189 public function __isset( $name ) {
4190 if ( in_array( $name, $this->compat_fields ) ) {
4191 return isset( $this->$name );
4196 * Make private/protected methods readable for backward compatibility.
4201 * @param callable $name Method to call.
4202 * @param array $arguments Arguments to pass when calling.
4203 * @return mixed|false Return value of the callback, false otherwise.
4205 public function __call( $name, $arguments ) {
4206 if ( in_array( $name, $this->compat_methods ) ) {
4207 return call_user_func_array( array( $this, $name ), $arguments );
4213 * Is the query for an existing archive page?
4215 * Month, Year, Category, Author, Post Type archive...
4221 public function is_archive() {
4222 return (bool) $this->is_archive;
4226 * Is the query for an existing post type archive page?
4230 * @param mixed $post_types Optional. Post type or array of posts types to check against.
4233 public function is_post_type_archive( $post_types = '' ) {
4234 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4235 return (bool) $this->is_post_type_archive;
4237 $post_type = $this->get( 'post_type' );
4238 if ( is_array( $post_type ) )
4239 $post_type = reset( $post_type );
4240 $post_type_object = get_post_type_object( $post_type );
4242 return in_array( $post_type_object->name, (array) $post_types );
4246 * Is the query for an existing attachment page?
4250 * @param mixed $attachment Attachment ID, title, slug, or array of such.
4253 public function is_attachment( $attachment = '' ) {
4254 if ( ! $this->is_attachment ) {
4258 if ( empty( $attachment ) ) {
4262 $attachment = array_map( 'strval', (array) $attachment );
4264 $post_obj = $this->get_queried_object();
4266 if ( in_array( (string) $post_obj->ID, $attachment ) ) {
4268 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4270 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4277 * Is the query for an existing author archive page?
4279 * If the $author parameter is specified, this function will additionally
4280 * check if the query is for one of the authors specified.
4284 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4287 public function is_author( $author = '' ) {
4288 if ( !$this->is_author )
4291 if ( empty($author) )
4294 $author_obj = $this->get_queried_object();
4296 $author = array_map( 'strval', (array) $author );
4298 if ( in_array( (string) $author_obj->ID, $author ) )
4300 elseif ( in_array( $author_obj->nickname, $author ) )
4302 elseif ( in_array( $author_obj->user_nicename, $author ) )
4309 * Is the query for an existing category archive page?
4311 * If the $category parameter is specified, this function will additionally
4312 * check if the query is for one of the categories specified.
4316 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4319 public function is_category( $category = '' ) {
4320 if ( !$this->is_category )
4323 if ( empty($category) )
4326 $cat_obj = $this->get_queried_object();
4328 $category = array_map( 'strval', (array) $category );
4330 if ( in_array( (string) $cat_obj->term_id, $category ) )
4332 elseif ( in_array( $cat_obj->name, $category ) )
4334 elseif ( in_array( $cat_obj->slug, $category ) )
4341 * Is the query for an existing tag archive page?
4343 * If the $tag parameter is specified, this function will additionally
4344 * check if the query is for one of the tags specified.
4348 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4351 public function is_tag( $tag = '' ) {
4352 if ( ! $this->is_tag )
4355 if ( empty( $tag ) )
4358 $tag_obj = $this->get_queried_object();
4360 $tag = array_map( 'strval', (array) $tag );
4362 if ( in_array( (string) $tag_obj->term_id, $tag ) )
4364 elseif ( in_array( $tag_obj->name, $tag ) )
4366 elseif ( in_array( $tag_obj->slug, $tag ) )
4373 * Is the query for an existing custom taxonomy archive page?
4375 * If the $taxonomy parameter is specified, this function will additionally
4376 * check if the query is for that specific $taxonomy.
4378 * If the $term parameter is specified in addition to the $taxonomy parameter,
4379 * this function will additionally check if the query is for one of the terms
4384 * @global array $wp_taxonomies
4386 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4387 * @param mixed $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4388 * @return bool True for custom taxonomy archive pages, false for built-in taxonomies (category and tag archives).
4390 public function is_tax( $taxonomy = '', $term = '' ) {
4391 global $wp_taxonomies;
4393 if ( !$this->is_tax )
4396 if ( empty( $taxonomy ) )
4399 $queried_object = $this->get_queried_object();
4400 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4401 $term_array = (array) $term;
4403 // Check that the taxonomy matches.
4404 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4407 // Only a Taxonomy provided.
4408 if ( empty( $term ) )
4411 return isset( $queried_object->term_id ) &&
4412 count( array_intersect(
4413 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4419 * Whether the current URL is within the comments popup window.
4426 public function is_comments_popup() {
4427 _deprecated_function( __FUNCTION__, '4.5.0' );
4433 * Is the query for an existing date archive?
4439 public function is_date() {
4440 return (bool) $this->is_date;
4444 * Is the query for an existing day archive?
4450 public function is_day() {
4451 return (bool) $this->is_day;
4455 * Is the query for a feed?
4459 * @param string|array $feeds Optional feed types to check.
4462 public function is_feed( $feeds = '' ) {
4463 if ( empty( $feeds ) || ! $this->is_feed )
4464 return (bool) $this->is_feed;
4465 $qv = $this->get( 'feed' );
4466 if ( 'feed' == $qv )
4467 $qv = get_default_feed();
4468 return in_array( $qv, (array) $feeds );
4472 * Is the query for a comments feed?
4478 public function is_comment_feed() {
4479 return (bool) $this->is_comment_feed;
4483 * Is the query for the front page of the site?
4485 * This is for what is displayed at your site's main URL.
4487 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4489 * If you set a static page for the front page of your site, this function will return
4490 * true when viewing that page.
4492 * Otherwise the same as @see WP_Query::is_home()
4496 * @return bool True, if front of site.
4498 public function is_front_page() {
4500 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4502 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4509 * Is the query for the blog homepage?
4511 * This is the page which shows the time based blog content of your site.
4513 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4515 * If you set a static page for the front page of your site, this function will return
4516 * true only on the page you set as the "Posts page".
4518 * @see WP_Query::is_front_page()
4522 * @return bool True if blog view homepage.
4524 public function is_home() {
4525 return (bool) $this->is_home;
4529 * Is the query for an existing month archive?
4535 public function is_month() {
4536 return (bool) $this->is_month;
4540 * Is the query for an existing single page?
4542 * If the $page parameter is specified, this function will additionally
4543 * check if the query is for one of the pages specified.
4545 * @see WP_Query::is_single()
4546 * @see WP_Query::is_singular()
4550 * @param int|string|array $page Optional. Page ID, title, slug, path, or array of such. Default empty.
4551 * @return bool Whether the query is for an existing single page.
4553 public function is_page( $page = '' ) {
4554 if ( !$this->is_page )
4557 if ( empty( $page ) )
4560 $page_obj = $this->get_queried_object();
4562 $page = array_map( 'strval', (array) $page );
4564 if ( in_array( (string) $page_obj->ID, $page ) ) {
4566 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4568 } elseif ( in_array( $page_obj->post_name, $page ) ) {
4571 foreach ( $page as $pagepath ) {
4572 if ( ! strpos( $pagepath, '/' ) ) {
4575 $pagepath_obj = get_page_by_path( $pagepath );
4577 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4587 * Is the query for paged result and not for the first page?
4593 public function is_paged() {
4594 return (bool) $this->is_paged;
4598 * Is the query for a post or page preview?
4604 public function is_preview() {
4605 return (bool) $this->is_preview;
4609 * Is the query for the robots file?
4615 public function is_robots() {
4616 return (bool) $this->is_robots;
4620 * Is the query for a search?
4626 public function is_search() {
4627 return (bool) $this->is_search;
4631 * Is the query for an existing single post?
4633 * Works for any post type, except attachments and pages
4635 * If the $post parameter is specified, this function will additionally
4636 * check if the query is for one of the Posts specified.
4638 * @see WP_Query::is_page()
4639 * @see WP_Query::is_singular()
4643 * @param int|string|array $post Optional. Post ID, title, slug, path, or array of such. Default empty.
4644 * @return bool Whether the query is for an existing single post.
4646 public function is_single( $post = '' ) {
4647 if ( !$this->is_single )
4653 $post_obj = $this->get_queried_object();
4655 $post = array_map( 'strval', (array) $post );
4657 if ( in_array( (string) $post_obj->ID, $post ) ) {
4659 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4661 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4664 foreach ( $post as $postpath ) {
4665 if ( ! strpos( $postpath, '/' ) ) {
4668 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4670 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4679 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4681 * If the $post_types parameter is specified, this function will additionally
4682 * check if the query is for one of the Posts Types specified.
4684 * @see WP_Query::is_page()
4685 * @see WP_Query::is_single()
4689 * @param string|array $post_types Optional. Post type or array of post types. Default empty.
4690 * @return bool Whether the query is for an existing single post of any of the given post types.
4692 public function is_singular( $post_types = '' ) {
4693 if ( empty( $post_types ) || !$this->is_singular )
4694 return (bool) $this->is_singular;
4696 $post_obj = $this->get_queried_object();
4698 return in_array( $post_obj->post_type, (array) $post_types );
4702 * Is the query for a specific time?
4708 public function is_time() {
4709 return (bool) $this->is_time;
4713 * Is the query for a trackback endpoint call?
4719 public function is_trackback() {
4720 return (bool) $this->is_trackback;
4724 * Is the query for an existing year archive?
4730 public function is_year() {
4731 return (bool) $this->is_year;
4735 * Is the query a 404 (returns no results)?
4741 public function is_404() {
4742 return (bool) $this->is_404;
4746 * Is the query for an embedded post?
4752 public function is_embed() {
4753 return (bool) $this->is_embed;
4757 * Is the query the main query?
4761 * @global WP_Query $wp_query Global WP_Query instance.
4765 public function is_main_query() {
4766 global $wp_the_query;
4767 return $wp_the_query === $this;
4771 * Set up global post data.
4774 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
4777 * @global WP_User $authordata
4778 * @global string|int|bool $currentday
4779 * @global string|int|bool $currentmonth
4781 * @global array $pages
4782 * @global int $multipage
4784 * @global int $numpages
4786 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
4787 * @return true True when finished.
4789 public function setup_postdata( $post ) {
4790 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4792 if ( ! ( $post instanceof WP_Post ) ) {
4793 $post = get_post( $post );
4800 $id = (int) $post->ID;
4802 $authordata = get_userdata($post->post_author);
4804 $currentday = mysql2date('d.m.y', $post->post_date, false);
4805 $currentmonth = mysql2date('m', $post->post_date, false);
4808 $page = $this->get( 'page' );
4813 * Force full post content when viewing the permalink for the $post,
4814 * or when on an RSS feed. Otherwise respect the 'more' tag.
4816 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4818 } elseif ( $this->is_feed() ) {
4824 $content = $post->post_content;
4825 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4826 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4827 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4828 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4830 // Ignore nextpage at the beginning of the content.
4831 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4832 $content = substr( $content, 15 );
4834 $pages = explode('<!--nextpage-->', $content);
4836 $pages = array( $post->post_content );
4840 * Filters the "pages" derived from splitting the post content.
4842 * "Pages" are determined by splitting the post content based on the presence
4843 * of `<!-- nextpage -->` tags.
4847 * @param array $pages Array of "pages" derived from the post content.
4848 * of `<!-- nextpage -->` tags..
4849 * @param WP_Post $post Current post object.
4851 $pages = apply_filters( 'content_pagination', $pages, $post );
4853 $numpages = count( $pages );
4855 if ( $numpages > 1 ) {
4865 * Fires once the post data has been setup.
4868 * @since 4.1.0 Introduced `$this` parameter.
4870 * @param WP_Post &$post The Post object (passed by reference).
4871 * @param WP_Query &$this The current Query object (passed by reference).
4873 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4878 * After looping through a nested query, this function
4879 * restores the $post global to the current post in this query.
4883 * @global WP_Post $post
4885 public function reset_postdata() {
4886 if ( ! empty( $this->post ) ) {
4887 $GLOBALS['post'] = $this->post;
4888 $this->setup_postdata( $this->post );
4893 * Lazyload term meta for posts in the loop.
4896 * @deprecated 4.5.0 See wp_queue_posts_for_term_meta_lazyload().
4898 * @param mixed $check
4899 * @param int $term_id
4902 public function lazyload_term_meta( $check, $term_id ) {
4903 _deprecated_function( __METHOD__, '4.5.0' );
4908 * Lazyload comment meta for comments in the loop.
4911 * @deprecated 4.5.0 See wp_queue_comments_for_comment_meta_lazyload().
4913 * @param mixed $check
4914 * @param int $comment_id
4917 public function lazyload_comment_meta( $check, $comment_id ) {
4918 _deprecated_function( __METHOD__, '4.5.0' );
4924 * Redirect old slugs to the correct permalink.
4926 * Attempts to find the current slug from the past slugs.
4930 * @global WP_Query $wp_query Global WP_Query instance.
4931 * @global wpdb $wpdb WordPress database abstraction object.
4933 function wp_old_slug_redirect() {
4936 if ( is_404() && '' !== $wp_query->query_vars['name'] ) :
4939 // Guess the current post_type based on the query vars.
4940 if ( get_query_var( 'post_type' ) ) {
4941 $post_type = get_query_var( 'post_type' );
4942 } elseif ( get_query_var( 'attachment' ) ) {
4943 $post_type = 'attachment';
4944 } elseif ( ! empty( $wp_query->query_vars['pagename'] ) ) {
4945 $post_type = 'page';
4947 $post_type = 'post';
4950 if ( is_array( $post_type ) ) {
4951 if ( count( $post_type ) > 1 )
4953 $post_type = reset( $post_type );
4956 // Do not attempt redirect for hierarchical post types
4957 if ( is_post_type_hierarchical( $post_type ) )
4960 $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']);
4962 // if year, monthnum, or day have been specified, make our query more precise
4963 // just in case there are multiple identical _wp_old_slug values
4964 if ( '' != $wp_query->query_vars['year'] )
4965 $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
4966 if ( '' != $wp_query->query_vars['monthnum'] )
4967 $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
4968 if ( '' != $wp_query->query_vars['day'] )
4969 $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
4971 $id = (int) $wpdb->get_var($query);
4976 $link = get_permalink( $id );
4978 if ( isset( $GLOBALS['wp_query']->query_vars['paged'] ) && $GLOBALS['wp_query']->query_vars['paged'] > 1 ) {
4979 $link = user_trailingslashit( trailingslashit( $link ) . 'page/' . $GLOBALS['wp_query']->query_vars['paged'] );
4980 } elseif( is_embed() ) {
4981 $link = user_trailingslashit( trailingslashit( $link ) . 'embed' );
4985 * Filters the old slug redirect URL.
4989 * @param string $link The redirect URL.
4991 $link = apply_filters( 'old_slug_redirect_url', $link );
4997 wp_redirect( $link, 301 ); // Permanent redirect
5003 * Set up global post data.
5006 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
5008 * @global WP_Query $wp_query Global WP_Query instance.
5010 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
5011 * @return bool True when finished.
5013 function setup_postdata( $post ) {
5016 if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
5017 return $wp_query->setup_postdata( $post );