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 http://codex.wordpress.org/The_Loop More information on The Loop.
15 * Retrieve variable in the WP_Query class.
17 * @see WP_Query::get()
21 * @param string $var The variable key to retrieve.
22 * @param mixed $default Value to return if the query variable is not set. Default ''.
25 function get_query_var( $var, $default = '' ) {
28 return $wp_query->get( $var, $default );
32 * Retrieve the currently-queried object. Wrapper for $wp_query->get_queried_object()
34 * @uses WP_Query::get_queried_object
41 function get_queried_object() {
43 return $wp_query->get_queried_object();
47 * Retrieve ID of the current queried object. Wrapper for $wp_query->get_queried_object_id()
49 * @uses WP_Query::get_queried_object_id()
56 function get_queried_object_id() {
58 return $wp_query->get_queried_object_id();
64 * @see WP_Query::set()
68 * @param string $var Query variable key.
72 function set_query_var($var, $value) {
75 return $wp_query->set($var, $value);
79 * Set up The Loop with query parameters.
81 * This will override the current WordPress Loop and shouldn't be used more than
82 * once. This must not be used within the WordPress Loop.
87 * @param string $query
88 * @return array List of posts
90 function query_posts($query) {
91 $GLOBALS['wp_query'] = new WP_Query();
92 return $GLOBALS['wp_query']->query($query);
96 * Destroy the previous query and set up a new query.
98 * This should be used after {@link query_posts()} and before another {@link
99 * query_posts()}. This will remove obscure bugs that occur when the previous
100 * wp_query object is not destroyed properly before another is set up.
105 function wp_reset_query() {
106 $GLOBALS['wp_query'] = $GLOBALS['wp_the_query'];
111 * After looping through a separate query, this function restores
112 * the $post global to the current post in the main query.
117 function wp_reset_postdata() {
120 if ( isset( $wp_query ) ) {
121 $wp_query->reset_postdata();
130 * Is the query for an existing archive page?
132 * Month, Year, Category, Author, Post Type archive...
134 * @see WP_Query::is_archive()
140 function is_archive() {
143 if ( ! isset( $wp_query ) ) {
144 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
148 return $wp_query->is_archive();
152 * Is the query for an existing post type archive page?
154 * @see WP_Query::is_post_type_archive()
158 * @param mixed $post_types Optional. Post type or array of posts types to check against.
161 function is_post_type_archive( $post_types = '' ) {
164 if ( ! isset( $wp_query ) ) {
165 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
169 return $wp_query->is_post_type_archive( $post_types );
173 * Is the query for an existing attachment page?
175 * @see WP_Query::is_attachment()
179 * @param int|string|array|object $attachment Attachment ID, title, slug, or array of such.
182 function is_attachment( $attachment = '' ) {
185 if ( ! isset( $wp_query ) ) {
186 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
190 return $wp_query->is_attachment( $attachment );
194 * Is the query for an existing author archive page?
196 * If the $author parameter is specified, this function will additionally
197 * check if the query is for one of the authors specified.
199 * @see WP_Query::is_author()
203 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
206 function is_author( $author = '' ) {
209 if ( ! isset( $wp_query ) ) {
210 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
214 return $wp_query->is_author( $author );
218 * Is the query for an existing category archive page?
220 * If the $category parameter is specified, this function will additionally
221 * check if the query is for one of the categories specified.
223 * @see WP_Query::is_category()
227 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
230 function is_category( $category = '' ) {
233 if ( ! isset( $wp_query ) ) {
234 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
238 return $wp_query->is_category( $category );
242 * Is the query for an existing tag archive page?
244 * If the $tag parameter is specified, this function will additionally
245 * check if the query is for one of the tags specified.
247 * @see WP_Query::is_tag()
251 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
254 function is_tag( $tag = '' ) {
257 if ( ! isset( $wp_query ) ) {
258 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
262 return $wp_query->is_tag( $tag );
266 * Is the query for an existing taxonomy archive page?
268 * If the $taxonomy parameter is specified, this function will additionally
269 * check if the query is for that specific $taxonomy.
271 * If the $term parameter is specified in addition to the $taxonomy parameter,
272 * this function will additionally check if the query is for one of the terms
275 * @see WP_Query::is_tax()
279 * @param string|array $taxonomy Optional. Taxonomy slug or slugs.
280 * @param int|string|array $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
283 function is_tax( $taxonomy = '', $term = '' ) {
286 if ( ! isset( $wp_query ) ) {
287 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
291 return $wp_query->is_tax( $taxonomy, $term );
295 * Whether the current URL is within the comments popup window.
297 * @see WP_Query::is_comments_popup()
303 function is_comments_popup() {
306 if ( ! isset( $wp_query ) ) {
307 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
311 return $wp_query->is_comments_popup();
315 * Is the query for an existing date archive?
317 * @see WP_Query::is_date()
326 if ( ! isset( $wp_query ) ) {
327 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
331 return $wp_query->is_date();
335 * Is the query for an existing day archive?
337 * @see WP_Query::is_day()
346 if ( ! isset( $wp_query ) ) {
347 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
351 return $wp_query->is_day();
355 * Is the query for a feed?
357 * @see WP_Query::is_feed()
361 * @param string|array $feeds Optional feed types to check.
364 function is_feed( $feeds = '' ) {
367 if ( ! isset( $wp_query ) ) {
368 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
372 return $wp_query->is_feed( $feeds );
376 * Is the query for a comments feed?
378 * @see WP_Query::is_comments_feed()
384 function is_comment_feed() {
387 if ( ! isset( $wp_query ) ) {
388 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
392 return $wp_query->is_comment_feed();
396 * Is the query for the front page of the site?
398 * This is for what is displayed at your site's main URL.
400 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
402 * If you set a static page for the front page of your site, this function will return
403 * true when viewing that page.
405 * Otherwise the same as @see is_home()
407 * @see WP_Query::is_front_page()
410 * @return bool True, if front of site.
412 function is_front_page() {
415 if ( ! isset( $wp_query ) ) {
416 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
420 return $wp_query->is_front_page();
424 * Is the query for the blog homepage?
426 * This is the page which shows the time based blog content of your site.
428 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
430 * If you set a static page for the front page of your site, this function will return
431 * true only on the page you set as the "Posts page".
433 * @see is_front_page()
435 * @see WP_Query::is_home()
439 * @return bool True if blog view homepage.
444 if ( ! isset( $wp_query ) ) {
445 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
449 return $wp_query->is_home();
453 * Is the query for an existing month archive?
455 * @see WP_Query::is_month()
461 function is_month() {
464 if ( ! isset( $wp_query ) ) {
465 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
469 return $wp_query->is_month();
473 * Is the query for an existing single page?
475 * If the $page parameter is specified, this function will additionally
476 * check if the query is for one of the pages specified.
481 * @see WP_Query::is_page()
485 * @param mixed $page Page ID, title, slug, or array of such.
488 function is_page( $page = '' ) {
491 if ( ! isset( $wp_query ) ) {
492 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
496 return $wp_query->is_page( $page );
500 * Is the query for paged result and not for the first page?
502 * @see WP_Query::is_paged()
508 function is_paged() {
511 if ( ! isset( $wp_query ) ) {
512 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
516 return $wp_query->is_paged();
520 * Is the query for a post or page preview?
522 * @see WP_Query::is_preview()
528 function is_preview() {
531 if ( ! isset( $wp_query ) ) {
532 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
536 return $wp_query->is_preview();
540 * Is the query for the robots file?
542 * @see WP_Query::is_robots()
548 function is_robots() {
551 if ( ! isset( $wp_query ) ) {
552 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
556 return $wp_query->is_robots();
560 * Is the query for a search?
562 * @see WP_Query::is_search()
568 function is_search() {
571 if ( ! isset( $wp_query ) ) {
572 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
576 return $wp_query->is_search();
580 * Is the query for an existing single post?
582 * Works for any post type, except attachments and pages
584 * If the $post parameter is specified, this function will additionally
585 * check if the query is for one of the Posts specified.
590 * @see WP_Query::is_single()
594 * @param mixed $post Post ID, title, slug, or array of such.
597 function is_single( $post = '' ) {
600 if ( ! isset( $wp_query ) ) {
601 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
605 return $wp_query->is_single( $post );
609 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
611 * If the $post_types parameter is specified, this function will additionally
612 * check if the query is for one of the Posts Types specified.
617 * @see WP_Query::is_singular()
621 * @param mixed $post_types Optional. Post Type or array of Post Types
624 function is_singular( $post_types = '' ) {
627 if ( ! isset( $wp_query ) ) {
628 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
632 return $wp_query->is_singular( $post_types );
636 * Is the query for a specific time?
638 * @see WP_Query::is_time()
647 if ( ! isset( $wp_query ) ) {
648 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
652 return $wp_query->is_time();
656 * Is the query for a trackback endpoint call?
658 * @see WP_Query::is_trackback()
664 function is_trackback() {
667 if ( ! isset( $wp_query ) ) {
668 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
672 return $wp_query->is_trackback();
676 * Is the query for an existing year archive?
678 * @see WP_Query::is_year()
687 if ( ! isset( $wp_query ) ) {
688 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
692 return $wp_query->is_year();
696 * Is the query a 404 (returns no results)?
698 * @see WP_Query::is_404()
707 if ( ! isset( $wp_query ) ) {
708 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
712 return $wp_query->is_404();
716 * Is the query the main query?
722 function is_main_query() {
723 if ( 'pre_get_posts' === current_filter() ) {
724 $message = sprintf( __( 'In <code>%1$s</code>, use the <code>%2$s</code> method, not the <code>%3$s</code> function. See %4$s.' ),
725 'pre_get_posts', 'WP_Query::is_main_query()', 'is_main_query()', __( 'http://codex.wordpress.org/Function_Reference/is_main_query' ) );
726 _doing_it_wrong( __FUNCTION__, $message, '3.7' );
730 return $wp_query->is_main_query();
734 * The Loop. Post loop control.
738 * Whether current WordPress query has results to loop over.
740 * @see WP_Query::have_posts()
746 function have_posts() {
749 return $wp_query->have_posts();
753 * Whether the caller is in the Loop.
758 * @return bool True if caller is within loop, false if loop hasn't started or ended.
760 function in_the_loop() {
763 return $wp_query->in_the_loop;
767 * Rewind the loop posts.
769 * @see WP_Query::rewind_posts()
775 function rewind_posts() {
778 return $wp_query->rewind_posts();
782 * Iterate the post index in the loop.
784 * @see WP_Query::the_post()
788 function the_post() {
791 $wp_query->the_post();
799 * Whether there are comments to loop over.
801 * @see WP_Query::have_comments()
807 function have_comments() {
809 return $wp_query->have_comments();
813 * Iterate comment index in the comment loop.
815 * @see WP_Query::the_comment()
821 function the_comment() {
823 return $wp_query->the_comment();
831 * The WordPress Query class.
833 * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
840 * Query vars set by the user
849 * Query vars, after parsing
855 public $query_vars = array();
858 * Taxonomy query, as passed to get_tax_sql()
862 * @var object WP_Tax_Query
867 * Metadata query container
871 * @var object WP_Meta_Query
873 public $meta_query = false;
876 * Date query container
880 * @var object WP_Date_Query
882 public $date_query = false;
885 * Holds the data for a single object that is queried.
887 * Holds the contents of a post, page, category, attachment.
893 public $queried_object;
896 * The ID of the queried object.
902 public $queried_object_id;
905 * Get post database query.
923 * The amount of posts for the current query.
929 public $post_count = 0;
932 * Index of the current item in the loop.
938 public $current_post = -1;
941 * Whether the loop has started and the caller is in the loop.
947 public $in_the_loop = false;
959 * The list of comments for current post.
968 * The amount of comments for the posts.
974 public $comment_count = 0;
977 * The index of the comment in the comment loop.
983 public $current_comment = -1;
986 * Current comment ID.
995 * The amount of found posts for the current query.
997 * If limit clause was not used, equals $post_count.
1003 public $found_posts = 0;
1006 * The amount of pages.
1012 public $max_num_pages = 0;
1015 * The amount of comment pages.
1021 public $max_num_comment_pages = 0;
1024 * Set if query is single post.
1030 public $is_single = false;
1033 * Set if query is preview of blog.
1039 public $is_preview = false;
1042 * Set if query returns a page.
1048 public $is_page = false;
1051 * Set if query is an archive list.
1057 public $is_archive = false;
1060 * Set if query is part of a date.
1066 public $is_date = false;
1069 * Set if query contains a year.
1075 public $is_year = false;
1078 * Set if query contains a month.
1084 public $is_month = false;
1087 * Set if query contains a day.
1093 public $is_day = false;
1096 * Set if query contains time.
1102 public $is_time = false;
1105 * Set if query contains an author.
1111 public $is_author = false;
1114 * Set if query contains category.
1120 public $is_category = false;
1123 * Set if query contains tag.
1129 public $is_tag = false;
1132 * Set if query contains taxonomy.
1138 public $is_tax = false;
1141 * Set if query was part of a search result.
1147 public $is_search = false;
1150 * Set if query is feed display.
1156 public $is_feed = false;
1159 * Set if query is comment feed display.
1165 public $is_comment_feed = false;
1168 * Set if query is trackback.
1174 public $is_trackback = false;
1177 * Set if query is blog homepage.
1183 public $is_home = false;
1186 * Set if query couldn't found anything.
1192 public $is_404 = false;
1195 * Set if query is within comments popup window.
1201 public $is_comments_popup = false;
1204 * Set if query is paged
1210 public $is_paged = false;
1213 * Set if query is part of administration page.
1219 public $is_admin = false;
1222 * Set if query is an attachment.
1228 public $is_attachment = false;
1231 * Set if is single, is a page, or is an attachment.
1237 public $is_singular = false;
1240 * Set if query is for robots.
1246 public $is_robots = false;
1249 * Set if query contains posts.
1251 * Basically, the homepage if the option isn't set for the static homepage.
1257 public $is_posts_page = false;
1260 * Set if query is for a post type archive.
1266 public $is_post_type_archive = false;
1269 * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
1270 * whether we have to re-parse because something has changed
1275 private $query_vars_hash = false;
1278 * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
1279 * via pre_get_posts hooks.
1284 private $query_vars_changed = true;
1287 * Set if post thumbnails are cached
1293 public $thumbnails_cached = false;
1296 * Cached list of search stopwords.
1304 * Resets query flags to false.
1306 * The query flags are what page info WordPress was able to figure out.
1311 private function init_query_flags() {
1312 $this->is_single = false;
1313 $this->is_preview = false;
1314 $this->is_page = false;
1315 $this->is_archive = false;
1316 $this->is_date = false;
1317 $this->is_year = false;
1318 $this->is_month = false;
1319 $this->is_day = false;
1320 $this->is_time = false;
1321 $this->is_author = false;
1322 $this->is_category = false;
1323 $this->is_tag = false;
1324 $this->is_tax = false;
1325 $this->is_search = false;
1326 $this->is_feed = false;
1327 $this->is_comment_feed = false;
1328 $this->is_trackback = false;
1329 $this->is_home = false;
1330 $this->is_404 = false;
1331 $this->is_comments_popup = false;
1332 $this->is_paged = false;
1333 $this->is_admin = false;
1334 $this->is_attachment = false;
1335 $this->is_singular = false;
1336 $this->is_robots = false;
1337 $this->is_posts_page = false;
1338 $this->is_post_type_archive = false;
1342 * Initiates object properties and sets default values.
1347 public function init() {
1348 unset($this->posts);
1349 unset($this->query);
1350 $this->query_vars = array();
1351 unset($this->queried_object);
1352 unset($this->queried_object_id);
1353 $this->post_count = 0;
1354 $this->current_post = -1;
1355 $this->in_the_loop = false;
1356 unset( $this->request );
1357 unset( $this->post );
1358 unset( $this->comments );
1359 unset( $this->comment );
1360 $this->comment_count = 0;
1361 $this->current_comment = -1;
1362 $this->found_posts = 0;
1363 $this->max_num_pages = 0;
1364 $this->max_num_comment_pages = 0;
1366 $this->init_query_flags();
1370 * Reparse the query vars.
1375 public function parse_query_vars() {
1376 $this->parse_query();
1380 * Fills in the query variables, which do not exist within the parameter.
1385 * @param array $array Defined query variables.
1386 * @return array Complete query variables with undefined ones filled in empty.
1388 public function fill_query_vars($array) {
1428 foreach ( $keys as $key ) {
1429 if ( !isset($array[$key]) )
1433 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in',
1434 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
1435 'author__in', 'author__not_in' );
1437 foreach ( $array_keys as $key ) {
1438 if ( !isset($array[$key]) )
1439 $array[$key] = array();
1445 * Parse a query string and set query type booleans.
1450 * @param string|array $query {
1451 * Optional. Array or string of Query parameters.
1453 * @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
1454 * @type int|string $author Author ID, or comma-separated list of IDs.
1455 * @type string $author_name User 'user_nicename'.
1456 * @type array $author__in An array of author IDs to query from.
1457 * @type array $author__not_in An array of author IDs not to query from.
1458 * @type bool $cache_results Whether to cache post information. Default true.
1459 * @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
1460 * @type array $category__and An array of category IDs (AND in).
1461 * @type array $category__in An array of category IDs (OR in, no children).
1462 * @type array $category__not_in An array of category IDs (NOT in).
1463 * @type string $category_name Use category slug (not name, this or any children).
1464 * @type int $comments_per_page The number of comments to return per page.
1465 * Default 'comments_per_page' option.
1466 * @type int|string $comments_popup Whether the query is within the comments popup. Default empty.
1467 * @type array $date_query An associative array of WP_Date_Query arguments.
1468 * {@see WP_Date_Query::__construct()}
1469 * @type int $day Day of the month. Default empty. Accepts numbers 1-31.
1470 * @type bool $exact Whether to search by exact keyword. Default false.
1471 * @type string|array $fields Which fields to return. Single field or all fields (string),
1472 * or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
1473 * Default all fields. Accepts 'ids', 'id=>parent'.
1474 * @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
1475 * @type bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
1476 * excludes stickies from 'post__in'. Accepts 1|true, 0|false.
1478 * @type int $m Combination YearMonth. Accepts any four-digit year and month
1479 * numbers 1-12. Default empty.
1480 * @type string $meta_compare Comparison operator to test the 'meta_value'.
1481 * @type string $meta_key Custom field key.
1482 * @type array $meta_query An associative array of WP_Meta_Query arguments.
1483 * {@see WP_Meta_Query->queries}
1484 * @type string $meta_value Custom field value.
1485 * @type int $meta_value_num Custom field value number.
1486 * @type int $menu_order The menu order of the posts.
1487 * @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
1488 * @type string $name Post slug.
1489 * @type bool $nopaging Show all posts (true) or paginate (false). Default false.
1490 * @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
1491 * performance. Default false.
1492 * @type int $offset The number of posts to offset before retrieval.
1493 * @type string $order Designates ascending or descending order of posts. Default 'DESC'.
1494 * Accepts 'ASC', 'DESC'.
1495 * @type string $orderby Sort retrieved posts by parameter. One or more options can be
1496 * passed. To use 'meta_value', or 'meta_value_num',
1497 * 'meta_key=keyname' must be also be defined. Default 'date'.
1498 * Accepts 'none', 'name', 'author', 'date', 'title', 'modified',
1499 * 'menu_order', 'parent', 'ID', 'rand', 'comment_count'.
1500 * @type int $p Post ID.
1501 * @type int $page Show the number of posts that would show up on page X of a
1502 * static front page.
1503 * @type int $paged The number of the current page.
1504 * @type int $page_id Page ID.
1505 * @type string $pagename Page slug.
1506 * @type string $perm Show posts if user has the appropriate capability.
1507 * @type array $post__in An array of post IDs to retrieve, sticky posts will be included
1508 * @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
1509 * @type array $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
1510 * separated IDs will NOT work.
1511 * @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
1513 * @type array $post_parent__in An array containing parent page IDs to query child pages from.
1514 * @type array $post_parent__not_in An array containing parent page IDs not to query child pages from.
1515 * @type string|array $post_type A post type slug (string) or array of post type slugs.
1516 * Default 'any' if using 'tax_query'.
1517 * @type string|array $post_status A post status (string) or array of post statuses.
1518 * @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
1519 * @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
1520 * 'posts_per_page' when is_archive(), or is_search() are true.
1521 * @type string $s Search keyword.
1522 * @type int $second Second of the minute. Default empty. Accepts numbers 0-60.
1523 * @type array $search_terms Array of search terms.
1524 * @type bool $sentence Whether to search by phrase. Default false.
1525 * @type bool $suppress_filters Whether to suppress filters. Default false.
1526 * @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
1527 * @type array $tag__and An array of tag ids (AND in).
1528 * @type array $tag__in An array of tag ids (OR in).
1529 * @type array $tag__not_in An array of tag ids (NOT in).
1530 * @type int $tag_id Tag id or comma-separated list of IDs.
1531 * @type array $tag_slug__and An array of tag slugs (AND in).
1532 * @type array $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
1533 * true. Note: a string of comma-separated IDs will NOT work.
1534 * @type array $tax_query An associative array of WP_Tax_Query arguments.
1535 * {@see WP_Tax_Query->queries}
1536 * @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
1537 * @type bool $update_post_term_cache Whether to update the post term cache. Default true.
1538 * @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
1539 * @type int $year The four-digit year. Default empty. Accepts any four-digit year.
1542 public function parse_query( $query = '' ) {
1543 if ( ! empty( $query ) ) {
1545 $this->query = $this->query_vars = wp_parse_args( $query );
1546 } elseif ( ! isset( $this->query ) ) {
1547 $this->query = $this->query_vars;
1550 $this->query_vars = $this->fill_query_vars($this->query_vars);
1551 $qv = &$this->query_vars;
1552 $this->query_vars_changed = true;
1554 if ( ! empty($qv['robots']) )
1555 $this->is_robots = true;
1557 $qv['p'] = absint($qv['p']);
1558 $qv['page_id'] = absint($qv['page_id']);
1559 $qv['year'] = absint($qv['year']);
1560 $qv['monthnum'] = absint($qv['monthnum']);
1561 $qv['day'] = absint($qv['day']);
1562 $qv['w'] = absint($qv['w']);
1563 $qv['m'] = preg_replace( '|[^0-9]|', '', $qv['m'] );
1564 $qv['paged'] = absint($qv['paged']);
1565 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1566 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
1567 $qv['pagename'] = trim( $qv['pagename'] );
1568 $qv['name'] = trim( $qv['name'] );
1569 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1570 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1571 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1572 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
1574 // Fairly insane upper bound for search string lengths.
1575 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
1579 // Compat. Map subpost to attachment.
1580 if ( '' != $qv['subpost'] )
1581 $qv['attachment'] = $qv['subpost'];
1582 if ( '' != $qv['subpost_id'] )
1583 $qv['attachment_id'] = $qv['subpost_id'];
1585 $qv['attachment_id'] = absint($qv['attachment_id']);
1587 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1588 $this->is_single = true;
1589 $this->is_attachment = true;
1590 } elseif ( '' != $qv['name'] ) {
1591 $this->is_single = true;
1592 } elseif ( $qv['p'] ) {
1593 $this->is_single = true;
1594 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1595 // If year, month, day, hour, minute, and second are set, a single
1596 // post is being queried.
1597 $this->is_single = true;
1598 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1599 $this->is_page = true;
1600 $this->is_single = false;
1602 // Look for archive queries. Dates, categories, authors, search, post type archives.
1604 if ( isset( $this->query['s'] ) ) {
1605 $this->is_search = true;
1608 if ( '' !== $qv['second'] ) {
1609 $this->is_time = true;
1610 $this->is_date = true;
1613 if ( '' !== $qv['minute'] ) {
1614 $this->is_time = true;
1615 $this->is_date = true;
1618 if ( '' !== $qv['hour'] ) {
1619 $this->is_time = true;
1620 $this->is_date = true;
1624 if ( ! $this->is_date ) {
1625 $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
1626 if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
1627 $qv['error'] = '404';
1629 $this->is_day = true;
1630 $this->is_date = true;
1635 if ( $qv['monthnum'] ) {
1636 if ( ! $this->is_date ) {
1637 if ( 12 < $qv['monthnum'] ) {
1638 $qv['error'] = '404';
1640 $this->is_month = true;
1641 $this->is_date = true;
1646 if ( $qv['year'] ) {
1647 if ( ! $this->is_date ) {
1648 $this->is_year = true;
1649 $this->is_date = true;
1654 $this->is_date = true;
1655 if ( strlen($qv['m']) > 9 ) {
1656 $this->is_time = true;
1657 } else if ( strlen($qv['m']) > 7 ) {
1658 $this->is_day = true;
1659 } else if ( strlen($qv['m']) > 5 ) {
1660 $this->is_month = true;
1662 $this->is_year = true;
1666 if ( '' != $qv['w'] ) {
1667 $this->is_date = true;
1670 $this->query_vars_hash = false;
1671 $this->parse_tax_query( $qv );
1673 foreach ( $this->tax_query->queries as $tax_query ) {
1674 if ( ! is_array( $tax_query ) ) {
1678 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
1679 switch ( $tax_query['taxonomy'] ) {
1681 $this->is_category = true;
1684 $this->is_tag = true;
1687 $this->is_tax = true;
1691 unset( $tax_query );
1693 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1694 $this->is_author = false;
1696 $this->is_author = true;
1699 if ( '' != $qv['author_name'] )
1700 $this->is_author = true;
1702 if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
1703 $post_type_obj = get_post_type_object( $qv['post_type'] );
1704 if ( ! empty( $post_type_obj->has_archive ) )
1705 $this->is_post_type_archive = true;
1708 if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
1709 $this->is_archive = true;
1712 if ( '' != $qv['feed'] )
1713 $this->is_feed = true;
1715 if ( '' != $qv['tb'] )
1716 $this->is_trackback = true;
1718 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
1719 $this->is_paged = true;
1721 if ( '' != $qv['comments_popup'] )
1722 $this->is_comments_popup = true;
1724 // if we're previewing inside the write screen
1725 if ( '' != $qv['preview'] )
1726 $this->is_preview = true;
1729 $this->is_admin = true;
1731 if ( false !== strpos($qv['feed'], 'comments-') ) {
1732 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1733 $qv['withcomments'] = 1;
1736 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1738 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1739 $this->is_comment_feed = true;
1741 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup || $this->is_robots ) )
1742 $this->is_home = true;
1744 // Correct is_* for page_on_front and page_for_posts
1745 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1746 $_query = wp_parse_args($this->query);
1747 // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
1748 if ( isset($_query['pagename']) && '' == $_query['pagename'] )
1749 unset($_query['pagename']);
1750 if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
1751 $this->is_page = true;
1752 $this->is_home = false;
1753 $qv['page_id'] = get_option('page_on_front');
1754 // Correct <!--nextpage--> for page_on_front
1755 if ( !empty($qv['paged']) ) {
1756 $qv['page'] = $qv['paged'];
1757 unset($qv['paged']);
1762 if ( '' != $qv['pagename'] ) {
1763 $this->queried_object = get_page_by_path($qv['pagename']);
1764 if ( !empty($this->queried_object) )
1765 $this->queried_object_id = (int) $this->queried_object->ID;
1767 unset($this->queried_object);
1769 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1770 $this->is_page = false;
1771 $this->is_home = true;
1772 $this->is_posts_page = true;
1776 if ( $qv['page_id'] ) {
1777 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1778 $this->is_page = false;
1779 $this->is_home = true;
1780 $this->is_posts_page = true;
1784 if ( !empty($qv['post_type']) ) {
1785 if ( is_array($qv['post_type']) )
1786 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1788 $qv['post_type'] = sanitize_key($qv['post_type']);
1791 if ( ! empty( $qv['post_status'] ) ) {
1792 if ( is_array( $qv['post_status'] ) )
1793 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1795 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1798 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1799 $this->is_comment_feed = false;
1801 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1802 // Done correcting is_* for page_on_front and page_for_posts
1804 if ( '404' == $qv['error'] )
1807 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1808 $this->query_vars_changed = false;
1811 * Fires after the main query vars have been parsed.
1815 * @param WP_Query &$this The WP_Query instance (passed by reference).
1817 do_action_ref_array( 'parse_query', array( &$this ) );
1821 * Parses various taxonomy related query vars.
1823 * For BC, this method is not marked as protected. See [28987].
1828 * @param array &$q The query variables
1830 function parse_tax_query( &$q ) {
1831 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1832 $tax_query = $q['tax_query'];
1834 $tax_query = array();
1837 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1838 $tax_query[] = array(
1839 'taxonomy' => $q['taxonomy'],
1840 'terms' => array( $q['term'] ),
1845 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1846 if ( 'post_tag' == $taxonomy )
1847 continue; // Handled further down in the $q['tag'] block
1849 if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1850 $tax_query_defaults = array(
1851 'taxonomy' => $taxonomy,
1855 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1856 $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1859 $term = $q[$t->query_var];
1861 if ( strpos($term, '+') !== false ) {
1862 $terms = preg_split( '/[+]+/', $term );
1863 foreach ( $terms as $term ) {
1864 $tax_query[] = array_merge( $tax_query_defaults, array(
1865 'terms' => array( $term )
1869 $tax_query[] = array_merge( $tax_query_defaults, array(
1870 'terms' => preg_split( '/[,]+/', $term )
1877 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1878 $cat_in = $cat_not_in = array();
1880 $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1881 $cat_array = array_map( 'intval', $cat_array );
1882 $q['cat'] = implode( ',', $cat_array );
1884 foreach ( $cat_array as $cat ) {
1888 $cat_not_in[] = abs( $cat );
1891 if ( ! empty( $cat_in ) ) {
1892 $tax_query[] = array(
1893 'taxonomy' => 'category',
1895 'field' => 'term_id',
1896 'include_children' => true
1900 if ( ! empty( $cat_not_in ) ) {
1901 $tax_query[] = array(
1902 'taxonomy' => 'category',
1903 'terms' => $cat_not_in,
1904 'field' => 'term_id',
1905 'operator' => 'NOT IN',
1906 'include_children' => true
1909 unset( $cat_array, $cat_in, $cat_not_in );
1912 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1913 $q['category__and'] = (array) $q['category__and'];
1914 if ( ! isset( $q['category__in'] ) )
1915 $q['category__in'] = array();
1916 $q['category__in'][] = absint( reset( $q['category__and'] ) );
1917 unset( $q['category__and'] );
1920 if ( ! empty( $q['category__in'] ) ) {
1921 $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1922 $tax_query[] = array(
1923 'taxonomy' => 'category',
1924 'terms' => $q['category__in'],
1925 'field' => 'term_id',
1926 'include_children' => false
1930 if ( ! empty($q['category__not_in']) ) {
1931 $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
1932 $tax_query[] = array(
1933 'taxonomy' => 'category',
1934 'terms' => $q['category__not_in'],
1935 'operator' => 'NOT IN',
1936 'include_children' => false
1940 if ( ! empty($q['category__and']) ) {
1941 $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
1942 $tax_query[] = array(
1943 'taxonomy' => 'category',
1944 'terms' => $q['category__and'],
1945 'field' => 'term_id',
1946 'operator' => 'AND',
1947 'include_children' => false
1952 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
1953 if ( strpos($q['tag'], ',') !== false ) {
1954 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
1955 foreach ( (array) $tags as $tag ) {
1956 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1957 $q['tag_slug__in'][] = $tag;
1959 } else if ( preg_match('/[+\r\n\t ]+/', $q['tag']) || !empty($q['cat']) ) {
1960 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
1961 foreach ( (array) $tags as $tag ) {
1962 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1963 $q['tag_slug__and'][] = $tag;
1966 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1967 $q['tag_slug__in'][] = $q['tag'];
1971 if ( !empty($q['tag_id']) ) {
1972 $q['tag_id'] = absint( $q['tag_id'] );
1973 $tax_query[] = array(
1974 'taxonomy' => 'post_tag',
1975 'terms' => $q['tag_id']
1979 if ( !empty($q['tag__in']) ) {
1980 $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
1981 $tax_query[] = array(
1982 'taxonomy' => 'post_tag',
1983 'terms' => $q['tag__in']
1987 if ( !empty($q['tag__not_in']) ) {
1988 $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
1989 $tax_query[] = array(
1990 'taxonomy' => 'post_tag',
1991 'terms' => $q['tag__not_in'],
1992 'operator' => 'NOT IN'
1996 if ( !empty($q['tag__and']) ) {
1997 $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
1998 $tax_query[] = array(
1999 'taxonomy' => 'post_tag',
2000 'terms' => $q['tag__and'],
2005 if ( !empty($q['tag_slug__in']) ) {
2006 $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
2007 $tax_query[] = array(
2008 'taxonomy' => 'post_tag',
2009 'terms' => $q['tag_slug__in'],
2014 if ( !empty($q['tag_slug__and']) ) {
2015 $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
2016 $tax_query[] = array(
2017 'taxonomy' => 'post_tag',
2018 'terms' => $q['tag_slug__and'],
2024 $this->tax_query = new WP_Tax_Query( $tax_query );
2027 * Fires after taxonomy-related query vars have been parsed.
2031 * @param WP_Query $this The WP_Query instance.
2033 do_action( 'parse_tax_query', $this );
2037 * Generate SQL for the WHERE clause based on passed search terms.
2041 * @global wpdb $wpdb
2042 * @param array $q Query variables.
2043 * @return string WHERE clause.
2045 protected function parse_search( &$q ) {
2050 // added slashes screw with quote grouping when done early, so done later
2051 $q['s'] = stripslashes( $q['s'] );
2052 if ( empty( $_GET['s'] ) && $this->is_main_query() )
2053 $q['s'] = urldecode( $q['s'] );
2054 // there are no line breaks in <input /> fields
2055 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
2056 $q['search_terms_count'] = 1;
2057 if ( ! empty( $q['sentence'] ) ) {
2058 $q['search_terms'] = array( $q['s'] );
2060 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
2061 $q['search_terms_count'] = count( $matches[0] );
2062 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
2063 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
2064 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
2065 $q['search_terms'] = array( $q['s'] );
2067 $q['search_terms'] = array( $q['s'] );
2071 $n = ! empty( $q['exact'] ) ? '' : '%';
2073 $q['search_orderby_title'] = array();
2074 foreach ( $q['search_terms'] as $term ) {
2076 $like = '%' . $wpdb->esc_like( $term ) . '%';
2077 $q['search_orderby_title'][] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like );
2080 $like = $n . $wpdb->esc_like( $term ) . $n;
2081 $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title LIKE %s) OR ($wpdb->posts.post_content LIKE %s))", $like, $like );
2082 $searchand = ' AND ';
2085 if ( ! empty( $search ) ) {
2086 $search = " AND ({$search}) ";
2087 if ( ! is_user_logged_in() )
2088 $search .= " AND ($wpdb->posts.post_password = '') ";
2095 * Check if the terms are suitable for searching.
2097 * Uses an array of stopwords (terms) that are excluded from the separate
2098 * term matching when searching for posts. The list of English stopwords is
2099 * the approximate search engines list, and is translatable.
2103 * @param array $terms Terms to check.
2104 * @return array Terms that are not stopwords.
2106 protected function parse_search_terms( $terms ) {
2107 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
2110 $stopwords = $this->get_search_stopwords();
2112 foreach ( $terms as $term ) {
2113 // keep before/after spaces when term is for exact match
2114 if ( preg_match( '/^".+"$/', $term ) )
2115 $term = trim( $term, "\"'" );
2117 $term = trim( $term, "\"' " );
2119 // Avoid single A-Z.
2120 if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z]$/i', $term ) ) )
2123 if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
2133 * Retrieve stopwords used when parsing search terms.
2137 * @return array Stopwords.
2139 protected function get_search_stopwords() {
2140 if ( isset( $this->stopwords ) )
2141 return $this->stopwords;
2143 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
2144 * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
2145 * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
2147 $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',
2148 'Comma-separated list of search stopwords in your language' ) );
2150 $stopwords = array();
2151 foreach( $words as $word ) {
2152 $word = trim( $word, "\r\n\t " );
2154 $stopwords[] = $word;
2158 * Filter stopwords used when parsing search terms.
2162 * @param array $stopwords Stopwords.
2164 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
2165 return $this->stopwords;
2169 * Generate SQL for the ORDER BY condition based on passed search terms.
2171 * @global wpdb $wpdb
2172 * @param array $q Query variables.
2173 * @return string ORDER BY clause.
2175 protected function parse_search_order( &$q ) {
2178 if ( $q['search_terms_count'] > 1 ) {
2179 $num_terms = count( $q['search_orderby_title'] );
2180 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
2182 $search_orderby = '(CASE ';
2183 // sentence match in 'post_title'
2184 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_title LIKE %s THEN 1 ", $like );
2186 // sanity limit, sort as sentence when more than 6 terms
2187 // (few searches are longer than 6 terms and most titles are not)
2188 if ( $num_terms < 7 ) {
2189 // all words in title
2190 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
2191 // any word in title, not needed when $num_terms == 1
2192 if ( $num_terms > 1 )
2193 $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
2196 // sentence match in 'post_content'
2197 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 4 ", $like );
2198 $search_orderby .= 'ELSE 5 END)';
2200 // single word or sentence search
2201 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2204 return $search_orderby;
2208 * If the passed orderby value is allowed, convert the alias to a
2209 * properly-prefixed orderby value.
2214 * @global wpdb $wpdb WordPress database abstraction object.
2216 * @param string $orderby Alias for the field to order by.
2217 * @return string|bool Table-prefixed value to used in the ORDER clause. False otherwise.
2219 protected function parse_orderby( $orderby ) {
2222 // Used to filter values.
2223 $allowed_keys = array(
2224 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2225 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2226 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2229 $primary_meta_key = '';
2230 $primary_meta_query = false;
2231 if ( ! empty( $this->meta_query->queries ) ) {
2232 $primary_meta_query = reset( $this->meta_query->queries );
2234 if ( ! empty( $primary_meta_query['key'] ) ) {
2235 $primary_meta_key = $primary_meta_query['key'];
2236 $allowed_keys[] = $primary_meta_key;
2239 $allowed_keys[] = 'meta_value';
2240 $allowed_keys[] = 'meta_value_num';
2243 if ( ! in_array( $orderby, $allowed_keys ) ) {
2247 switch ( $orderby ) {
2252 case 'post_modified':
2257 case 'comment_count':
2258 $orderby = "$wpdb->posts.{$orderby}";
2261 $orderby = 'RAND()';
2263 case $primary_meta_key:
2265 if ( ! empty( $primary_meta_query['type'] ) ) {
2266 $sql_type = $this->meta_query->get_cast_for_type( $primary_meta_query['type'] );
2267 $orderby = "CAST($wpdb->postmeta.meta_value AS {$sql_type})";
2269 $orderby = "$wpdb->postmeta.meta_value";
2272 case 'meta_value_num':
2273 $orderby = "$wpdb->postmeta.meta_value+0";
2276 $orderby = "$wpdb->posts.post_" . $orderby;
2284 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2289 * @param string $order The 'order' query variable.
2290 * @return string The sanitized 'order' query variable.
2292 protected function parse_order( $order ) {
2293 if ( ! is_string( $order ) || empty( $order ) ) {
2297 if ( 'ASC' === strtoupper( $order ) ) {
2305 * Sets the 404 property and saves whether query is feed.
2310 public function set_404() {
2311 $is_feed = $this->is_feed;
2313 $this->init_query_flags();
2314 $this->is_404 = true;
2316 $this->is_feed = $is_feed;
2320 * Retrieve query variable.
2325 * @param string $query_var Query variable key.
2326 * @param mixed $default Value to return if the query variable is not set. Default ''.
2329 public function get( $query_var, $default = '' ) {
2330 if ( isset( $this->query_vars[ $query_var ] ) ) {
2331 return $this->query_vars[ $query_var ];
2338 * Set query variable.
2343 * @param string $query_var Query variable key.
2344 * @param mixed $value Query variable value.
2346 public function set($query_var, $value) {
2347 $this->query_vars[$query_var] = $value;
2351 * Retrieve the posts based on query variables.
2353 * There are a few filters and actions that can be used to modify the post
2359 * @return array List of posts.
2361 public function get_posts() {
2364 $this->parse_query();
2367 * Fires after the query variable object is created, but before the actual query is run.
2369 * Note: If using conditional tags, use the method versions within the passed instance
2370 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2371 * like is_main_query() test against the global $wp_query instance, not the passed one.
2375 * @param WP_Query &$this The WP_Query instance (passed by reference).
2377 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2380 $q = &$this->query_vars;
2382 // Fill again in case pre_get_posts unset some vars.
2383 $q = $this->fill_query_vars($q);
2386 $this->meta_query = new WP_Meta_Query();
2387 $this->meta_query->parse_query_vars( $q );
2389 // Set a flag if a pre_get_posts hook changed the query vars.
2390 $hash = md5( serialize( $this->query_vars ) );
2391 if ( $hash != $this->query_vars_hash ) {
2392 $this->query_vars_changed = true;
2393 $this->query_vars_hash = $hash;
2397 // First let's clear some variables
2400 $whichmimetype = '';
2406 $post_status_join = false;
2409 if ( isset( $q['caller_get_posts'] ) ) {
2410 _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2411 if ( !isset( $q['ignore_sticky_posts'] ) )
2412 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2415 if ( !isset( $q['ignore_sticky_posts'] ) )
2416 $q['ignore_sticky_posts'] = false;
2418 if ( !isset($q['suppress_filters']) )
2419 $q['suppress_filters'] = false;
2421 if ( !isset($q['cache_results']) ) {
2422 if ( wp_using_ext_object_cache() )
2423 $q['cache_results'] = false;
2425 $q['cache_results'] = true;
2428 if ( !isset($q['update_post_term_cache']) )
2429 $q['update_post_term_cache'] = true;
2431 if ( !isset($q['update_post_meta_cache']) )
2432 $q['update_post_meta_cache'] = true;
2434 if ( !isset($q['post_type']) ) {
2435 if ( $this->is_search )
2436 $q['post_type'] = 'any';
2438 $q['post_type'] = '';
2440 $post_type = $q['post_type'];
2441 if ( empty( $q['posts_per_page'] ) ) {
2442 $q['posts_per_page'] = get_option( 'posts_per_page' );
2444 if ( isset($q['showposts']) && $q['showposts'] ) {
2445 $q['showposts'] = (int) $q['showposts'];
2446 $q['posts_per_page'] = $q['showposts'];
2448 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2449 $q['posts_per_page'] = $q['posts_per_archive_page'];
2450 if ( !isset($q['nopaging']) ) {
2451 if ( $q['posts_per_page'] == -1 ) {
2452 $q['nopaging'] = true;
2454 $q['nopaging'] = false;
2458 if ( $this->is_feed ) {
2459 // This overrides posts_per_page.
2460 if ( ! empty( $q['posts_per_rss'] ) ) {
2461 $q['posts_per_page'] = $q['posts_per_rss'];
2463 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2465 $q['nopaging'] = false;
2467 $q['posts_per_page'] = (int) $q['posts_per_page'];
2468 if ( $q['posts_per_page'] < -1 )
2469 $q['posts_per_page'] = abs($q['posts_per_page']);
2470 else if ( $q['posts_per_page'] == 0 )
2471 $q['posts_per_page'] = 1;
2473 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2474 $q['comments_per_page'] = get_option('comments_per_page');
2476 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2477 $this->is_page = true;
2478 $this->is_home = false;
2479 $q['page_id'] = get_option('page_on_front');
2482 if ( isset($q['page']) ) {
2483 $q['page'] = trim($q['page'], '/');
2484 $q['page'] = absint($q['page']);
2487 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2488 if ( isset($q['no_found_rows']) )
2489 $q['no_found_rows'] = (bool) $q['no_found_rows'];
2491 $q['no_found_rows'] = false;
2493 switch ( $q['fields'] ) {
2495 $fields = "$wpdb->posts.ID";
2498 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2501 $fields = "$wpdb->posts.*";
2504 if ( '' !== $q['menu_order'] )
2505 $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2507 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2509 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2510 if ( strlen($q['m']) > 5 )
2511 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2512 if ( strlen($q['m']) > 7 )
2513 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2514 if ( strlen($q['m']) > 9 )
2515 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2516 if ( strlen($q['m']) > 11 )
2517 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2518 if ( strlen($q['m']) > 13 )
2519 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2522 // Handle the other individual date parameters
2523 $date_parameters = array();
2525 if ( '' !== $q['hour'] )
2526 $date_parameters['hour'] = $q['hour'];
2528 if ( '' !== $q['minute'] )
2529 $date_parameters['minute'] = $q['minute'];
2531 if ( '' !== $q['second'] )
2532 $date_parameters['second'] = $q['second'];
2535 $date_parameters['year'] = $q['year'];
2537 if ( $q['monthnum'] )
2538 $date_parameters['monthnum'] = $q['monthnum'];
2541 $date_parameters['week'] = $q['w'];
2544 $date_parameters['day'] = $q['day'];
2546 if ( $date_parameters ) {
2547 $date_query = new WP_Date_Query( array( $date_parameters ) );
2548 $where .= $date_query->get_sql();
2550 unset( $date_parameters, $date_query );
2552 // Handle complex date queries
2553 if ( ! empty( $q['date_query'] ) ) {
2554 $this->date_query = new WP_Date_Query( $q['date_query'] );
2555 $where .= $this->date_query->get_sql();
2559 // If we've got a post_type AND it's not "any" post_type.
2560 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2561 foreach ( (array)$q['post_type'] as $_post_type ) {
2562 $ptype_obj = get_post_type_object($_post_type);
2563 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2566 if ( ! $ptype_obj->hierarchical ) {
2567 // Non-hierarchical post types can directly use 'name'.
2568 $q['name'] = $q[ $ptype_obj->query_var ];
2570 // Hierarchical post types will operate through 'pagename'.
2571 $q['pagename'] = $q[ $ptype_obj->query_var ];
2575 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2581 if ( '' != $q['name'] ) {
2582 $q['name'] = sanitize_title_for_query( $q['name'] );
2583 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2584 } elseif ( '' != $q['pagename'] ) {
2585 if ( isset($this->queried_object_id) ) {
2586 $reqpage = $this->queried_object_id;
2588 if ( 'page' != $q['post_type'] ) {
2589 foreach ( (array)$q['post_type'] as $_post_type ) {
2590 $ptype_obj = get_post_type_object($_post_type);
2591 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2594 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2600 $reqpage = get_page_by_path($q['pagename']);
2602 if ( !empty($reqpage) )
2603 $reqpage = $reqpage->ID;
2608 $page_for_posts = get_option('page_for_posts');
2609 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2610 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2611 $q['name'] = $q['pagename'];
2612 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2613 $reqpage_obj = get_post( $reqpage );
2614 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2615 $this->is_attachment = true;
2616 $post_type = $q['post_type'] = 'attachment';
2617 $this->is_page = true;
2618 $q['attachment_id'] = $reqpage;
2621 } elseif ( '' != $q['attachment'] ) {
2622 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2623 $q['name'] = $q['attachment'];
2624 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2628 if ( intval($q['comments_popup']) )
2629 $q['p'] = absint($q['comments_popup']);
2631 // If an attachment is requested by number, let it supersede any post number.
2632 if ( $q['attachment_id'] )
2633 $q['p'] = absint($q['attachment_id']);
2635 // If a post number is specified, load that post
2637 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2638 } elseif ( $q['post__in'] ) {
2639 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2640 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2641 } elseif ( $q['post__not_in'] ) {
2642 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
2643 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2646 if ( is_numeric( $q['post_parent'] ) ) {
2647 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2648 } elseif ( $q['post_parent__in'] ) {
2649 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2650 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2651 } elseif ( $q['post_parent__not_in'] ) {
2652 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
2653 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2656 if ( $q['page_id'] ) {
2657 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2658 $q['p'] = $q['page_id'];
2659 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2663 // If a search pattern is specified, load the posts that match.
2664 if ( ! empty( $q['s'] ) ) {
2665 $search = $this->parse_search( $q );
2669 * Filter the search SQL that is used in the WHERE clause of WP_Query.
2673 * @param string $search Search SQL for WHERE clause.
2674 * @param WP_Query $this The current WP_Query object.
2676 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2679 if ( !$this->is_singular ) {
2680 $this->parse_tax_query( $q );
2682 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2684 $join .= $clauses['join'];
2685 $where .= $clauses['where'];
2688 if ( $this->is_tax ) {
2689 if ( empty($post_type) ) {
2690 // Do a fully inclusive search for currently registered post types of queried taxonomies
2691 $post_type = array();
2692 $taxonomies = array_keys( $this->tax_query->queried_terms );
2693 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2694 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2695 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2700 elseif ( count( $post_type ) == 1 )
2701 $post_type = $post_type[0];
2703 $post_status_join = true;
2704 } elseif ( in_array('attachment', (array) $post_type) ) {
2705 $post_status_join = true;
2710 * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2711 * 'category_name' vars are set for backward compatibility.
2713 if ( ! empty( $this->tax_query->queried_terms ) ) {
2716 * Set 'taxonomy', 'term', and 'term_id' to the
2717 * first taxonomy other than 'post_tag' or 'category'.
2719 if ( ! isset( $q['taxonomy'] ) ) {
2720 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2721 if ( empty( $queried_items['terms'][0] ) ) {
2725 if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2726 $q['taxonomy'] = $queried_taxonomy;
2728 if ( 'slug' === $queried_items['field'] ) {
2729 $q['term'] = $queried_items['terms'][0];
2731 $q['term_id'] = $queried_items['terms'][0];
2737 // 'cat', 'category_name', 'tag_id'
2738 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2739 if ( empty( $queried_items['terms'][0] ) ) {
2743 if ( 'category' === $queried_taxonomy ) {
2744 $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2746 $this->set( 'cat', $the_cat->term_id );
2747 $this->set( 'category_name', $the_cat->slug );
2752 if ( 'post_tag' === $queried_taxonomy ) {
2753 $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2755 $this->set( 'tag_id', $the_tag->term_id );
2762 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2763 $groupby = "{$wpdb->posts}.ID";
2766 // Author/user stuff
2768 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2769 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2770 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2771 foreach ( $authors as $author ) {
2772 $key = $author > 0 ? 'author__in' : 'author__not_in';
2773 $q[$key][] = abs( $author );
2775 $q['author'] = implode( ',', $authors );
2778 if ( ! empty( $q['author__not_in'] ) ) {
2779 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2780 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2781 } elseif ( ! empty( $q['author__in'] ) ) {
2782 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2783 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2786 // Author stuff for nice URLs
2788 if ( '' != $q['author_name'] ) {
2789 if ( strpos($q['author_name'], '/') !== false ) {
2790 $q['author_name'] = explode('/', $q['author_name']);
2791 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2792 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2794 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2797 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2798 $q['author'] = get_user_by('slug', $q['author_name']);
2800 $q['author'] = $q['author']->ID;
2801 $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2804 // MIME-Type stuff for attachment browsing
2806 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2807 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2809 $where .= $search . $whichauthor . $whichmimetype;
2811 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2812 if ( ! isset( $q['order'] ) ) {
2813 $q['order'] = $rand ? '' : 'DESC';
2815 $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2819 if ( empty( $q['orderby'] ) ) {
2821 * Boolean false or empty array blanks out ORDER BY,
2822 * while leaving the value unset or otherwise empty sets the default.
2824 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2827 $orderby = "$wpdb->posts.post_date " . $q['order'];
2829 } elseif ( 'none' == $q['orderby'] ) {
2831 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2832 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2833 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2834 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2836 $orderby_array = array();
2837 if ( is_array( $q['orderby'] ) ) {
2838 foreach ( $q['orderby'] as $_orderby => $order ) {
2839 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2840 $parsed = $this->parse_orderby( $orderby );
2846 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2848 $orderby = implode( ', ', $orderby_array );
2851 $q['orderby'] = urldecode( $q['orderby'] );
2852 $q['orderby'] = addslashes_gpc( $q['orderby'] );
2854 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
2855 $parsed = $this->parse_orderby( $orderby );
2856 // Only allow certain values for safety.
2861 $orderby_array[] = $parsed;
2863 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
2865 if ( empty( $orderby ) ) {
2866 $orderby = "$wpdb->posts.post_date " . $q['order'];
2867 } elseif ( ! empty( $q['order'] ) ) {
2868 $orderby .= " {$q['order']}";
2873 // Order search results by relevance only when another "orderby" is not specified in the query.
2874 if ( ! empty( $q['s'] ) ) {
2875 $search_orderby = '';
2876 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
2877 $search_orderby = $this->parse_search_order( $q );
2880 * Filter the ORDER BY used when ordering search results.
2884 * @param string $search_orderby The ORDER BY clause.
2885 * @param WP_Query $this The current WP_Query instance.
2887 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
2888 if ( $search_orderby )
2889 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
2892 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
2893 $post_type_cap = 'multiple_post_type';
2895 if ( is_array( $post_type ) )
2896 $post_type = reset( $post_type );
2897 $post_type_object = get_post_type_object( $post_type );
2898 if ( empty( $post_type_object ) )
2899 $post_type_cap = $post_type;
2902 if ( isset( $q['post_password'] ) ) {
2903 $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
2904 if ( empty( $q['perm'] ) ) {
2905 $q['perm'] = 'readable';
2907 } elseif ( isset( $q['has_password'] ) ) {
2908 $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
2911 if ( 'any' == $post_type ) {
2912 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
2913 if ( empty( $in_search_post_types ) )
2914 $where .= ' AND 1=0 ';
2916 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')";
2917 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
2918 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
2919 } elseif ( ! empty( $post_type ) ) {
2920 $where .= " AND $wpdb->posts.post_type = '$post_type'";
2921 $post_type_object = get_post_type_object ( $post_type );
2922 } elseif ( $this->is_attachment ) {
2923 $where .= " AND $wpdb->posts.post_type = 'attachment'";
2924 $post_type_object = get_post_type_object ( 'attachment' );
2925 } elseif ( $this->is_page ) {
2926 $where .= " AND $wpdb->posts.post_type = 'page'";
2927 $post_type_object = get_post_type_object ( 'page' );
2929 $where .= " AND $wpdb->posts.post_type = 'post'";
2930 $post_type_object = get_post_type_object ( 'post' );
2933 $edit_cap = 'edit_post';
2934 $read_cap = 'read_post';
2936 if ( ! empty( $post_type_object ) ) {
2937 $edit_others_cap = $post_type_object->cap->edit_others_posts;
2938 $read_private_cap = $post_type_object->cap->read_private_posts;
2940 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
2941 $read_private_cap = 'read_private_' . $post_type_cap . 's';
2944 $user_id = get_current_user_id();
2946 if ( ! empty( $q['post_status'] ) ) {
2947 $statuswheres = array();
2948 $q_status = $q['post_status'];
2949 if ( ! is_array( $q_status ) )
2950 $q_status = explode(',', $q_status);
2951 $r_status = array();
2952 $p_status = array();
2953 $e_status = array();
2954 if ( in_array( 'any', $q_status ) ) {
2955 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
2956 if ( ! in_array( $status, $q_status ) ) {
2957 $e_status[] = "$wpdb->posts.post_status <> '$status'";
2961 foreach ( get_post_stati() as $status ) {
2962 if ( in_array( $status, $q_status ) ) {
2963 if ( 'private' == $status )
2964 $p_status[] = "$wpdb->posts.post_status = '$status'";
2966 $r_status[] = "$wpdb->posts.post_status = '$status'";
2971 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
2972 $r_status = array_merge($r_status, $p_status);
2976 if ( !empty($e_status) ) {
2977 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
2979 if ( !empty($r_status) ) {
2980 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
2981 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
2983 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
2985 if ( !empty($p_status) ) {
2986 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
2987 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
2989 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
2991 if ( $post_status_join ) {
2992 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
2993 foreach ( $statuswheres as $index => $statuswhere )
2994 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
2996 $where_status = implode( ' OR ', $statuswheres );
2997 if ( ! empty( $where_status ) ) {
2998 $where .= " AND ($where_status)";
3000 } elseif ( !$this->is_singular ) {
3001 $where .= " AND ($wpdb->posts.post_status = 'publish'";
3003 // Add public states.
3004 $public_states = get_post_stati( array('public' => true) );
3005 foreach ( (array) $public_states as $state ) {
3006 if ( 'publish' == $state ) // Publish is hard-coded above.
3008 $where .= " OR $wpdb->posts.post_status = '$state'";
3011 if ( $this->is_admin ) {
3012 // Add protected states that should show in the admin all list.
3013 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3014 foreach ( (array) $admin_all_states as $state )
3015 $where .= " OR $wpdb->posts.post_status = '$state'";
3018 if ( is_user_logged_in() ) {
3019 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3020 $private_states = get_post_stati( array('private' => true) );
3021 foreach ( (array) $private_states as $state )
3022 $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'";
3028 if ( !empty( $this->meta_query->queries ) ) {
3029 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
3030 $join .= $clauses['join'];
3031 $where .= $clauses['where'];
3035 * Apply filters on where and join prior to paging so that any
3036 * manipulations to them are reflected in the paging by day queries.
3038 if ( !$q['suppress_filters'] ) {
3040 * Filter the WHERE clause of the query.
3044 * @param string $where The WHERE clause of the query.
3045 * @param WP_Query &$this The WP_Query instance (passed by reference).
3047 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3050 * Filter the JOIN clause of the query.
3054 * @param string $where The JOIN clause of the query.
3055 * @param WP_Query &$this The WP_Query instance (passed by reference).
3057 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3061 if ( empty($q['nopaging']) && !$this->is_singular ) {
3062 $page = absint($q['paged']);
3066 if ( empty($q['offset']) ) {
3067 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3068 } else { // we're ignoring $page and using 'offset'
3069 $q['offset'] = absint($q['offset']);
3070 $pgstrt = $q['offset'] . ', ';
3072 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3076 if ( $this->is_comment_feed && ! $this->is_singular ) {
3077 if ( $this->is_archive || $this->is_search ) {
3078 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3079 $cwhere = "WHERE comment_approved = '1' $where";
3080 $cgroupby = "$wpdb->comments.comment_id";
3081 } else { // Other non singular e.g. front
3082 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3083 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
3087 if ( !$q['suppress_filters'] ) {
3089 * Filter the JOIN clause of the comments feed query before sending.
3093 * @param string $cjoin The JOIN clause of the query.
3094 * @param WP_Query &$this The WP_Query instance (passed by reference).
3096 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3099 * Filter the WHERE clause of the comments feed query before sending.
3103 * @param string $cwhere The WHERE clause of the query.
3104 * @param WP_Query &$this The WP_Query instance (passed by reference).
3106 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3109 * Filter the GROUP BY clause of the comments feed query before sending.
3113 * @param string $cgroupby The GROUP BY clause of the query.
3114 * @param WP_Query &$this The WP_Query instance (passed by reference).
3116 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3119 * Filter the ORDER BY clause of the comments feed query before sending.
3123 * @param string $corderby The ORDER BY clause of the query.
3124 * @param WP_Query &$this The WP_Query instance (passed by reference).
3126 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3129 * Filter the LIMIT clause of the comments feed query before sending.
3133 * @param string $climits The JOIN clause of the query.
3134 * @param WP_Query &$this The WP_Query instance (passed by reference).
3136 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3138 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3139 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3141 $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3142 $this->comment_count = count($this->comments);
3144 $post_ids = array();
3146 foreach ( $this->comments as $comment )
3147 $post_ids[] = (int) $comment->comment_post_ID;
3149 $post_ids = join(',', $post_ids);
3152 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3157 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3160 * Apply post-paging filters on where and join. Only plugins that
3161 * manipulate paging queries should use these hooks.
3163 if ( !$q['suppress_filters'] ) {
3165 * Filter the WHERE clause of the query.
3167 * Specifically for manipulating paging queries.
3171 * @param string $where The WHERE clause of the query.
3172 * @param WP_Query &$this The WP_Query instance (passed by reference).
3174 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3177 * Filter the GROUP BY clause of the query.
3181 * @param string $groupby The GROUP BY clause of the query.
3182 * @param WP_Query &$this The WP_Query instance (passed by reference).
3184 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3187 * Filter the JOIN clause of the query.
3189 * Specifically for manipulating paging queries.
3193 * @param string $join The JOIN clause of the query.
3194 * @param WP_Query &$this The WP_Query instance (passed by reference).
3196 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3199 * Filter the ORDER BY clause of the query.
3203 * @param string $orderby The ORDER BY clause of the query.
3204 * @param WP_Query &$this The WP_Query instance (passed by reference).
3206 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3209 * Filter the DISTINCT clause of the query.
3213 * @param string $distinct The DISTINCT clause of the query.
3214 * @param WP_Query &$this The WP_Query instance (passed by reference).
3216 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3219 * Filter the LIMIT clause of the query.
3223 * @param string $limits The LIMIT clause of the query.
3224 * @param WP_Query &$this The WP_Query instance (passed by reference).
3226 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3229 * Filter the SELECT clause of the query.
3233 * @param string $fields The SELECT clause of the query.
3234 * @param WP_Query &$this The WP_Query instance (passed by reference).
3236 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3239 * Filter all query clauses at once, for convenience.
3241 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3242 * fields (SELECT), and LIMITS clauses.
3246 * @param array $clauses The list of clauses for the query.
3247 * @param WP_Query &$this The WP_Query instance (passed by reference).
3249 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3251 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3252 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3253 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3254 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3255 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3256 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3257 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3261 * Fires to announce the query's current selection parameters.
3263 * For use by caching plugins.
3267 * @param string $selection The assembled selection query.
3269 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3272 * Filter again for the benefit of caching plugins.
3273 * Regular plugins should use the hooks above.
3275 if ( !$q['suppress_filters'] ) {
3277 * Filter the WHERE clause of the query.
3279 * For use by caching plugins.
3283 * @param string $where The WHERE clause of the query.
3284 * @param WP_Query &$this The WP_Query instance (passed by reference).
3286 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3289 * Filter the GROUP BY clause of the query.
3291 * For use by caching plugins.
3295 * @param string $groupby The GROUP BY clause of the query.
3296 * @param WP_Query &$this The WP_Query instance (passed by reference).
3298 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3301 * Filter the JOIN clause of the query.
3303 * For use by caching plugins.
3307 * @param string $join The JOIN clause of the query.
3308 * @param WP_Query &$this The WP_Query instance (passed by reference).
3310 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3313 * Filter the ORDER BY clause of the query.
3315 * For use by caching plugins.
3319 * @param string $orderby The ORDER BY clause of the query.
3320 * @param WP_Query &$this The WP_Query instance (passed by reference).
3322 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3325 * Filter the DISTINCT clause of the query.
3327 * For use by caching plugins.
3331 * @param string $distinct The DISTINCT clause of the query.
3332 * @param WP_Query &$this The WP_Query instance (passed by reference).
3334 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3337 * Filter the SELECT clause of the query.
3339 * For use by caching plugins.
3343 * @param string $fields The SELECT clause of the query.
3344 * @param WP_Query &$this The WP_Query instance (passed by reference).
3346 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3349 * Filter the LIMIT clause of the query.
3351 * For use by caching plugins.
3355 * @param string $limits The LIMIT clause of the query.
3356 * @param WP_Query &$this The WP_Query instance (passed by reference).
3358 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3361 * Filter all query clauses at once, for convenience.
3363 * For use by caching plugins.
3365 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3366 * fields (SELECT), and LIMITS clauses.
3370 * @param array $pieces The pieces of the query.
3371 * @param WP_Query &$this The WP_Query instance (passed by reference).
3373 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3375 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3376 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3377 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3378 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3379 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3380 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3381 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3384 if ( ! empty($groupby) )
3385 $groupby = 'GROUP BY ' . $groupby;
3386 if ( !empty( $orderby ) )
3387 $orderby = 'ORDER BY ' . $orderby;
3390 if ( !$q['no_found_rows'] && !empty($limits) )
3391 $found_rows = 'SQL_CALC_FOUND_ROWS';
3393 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3395 if ( !$q['suppress_filters'] ) {
3397 * Filter the completed SQL query before sending.
3401 * @param array $request The complete SQL query.
3402 * @param WP_Query &$this The WP_Query instance (passed by reference).
3404 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3407 if ( 'ids' == $q['fields'] ) {
3408 $this->posts = $wpdb->get_col( $this->request );
3409 $this->post_count = count( $this->posts );
3410 $this->set_found_posts( $q, $limits );
3412 return array_map( 'intval', $this->posts );
3415 if ( 'id=>parent' == $q['fields'] ) {
3416 $this->posts = $wpdb->get_results( $this->request );
3417 $this->post_count = count( $this->posts );
3418 $this->set_found_posts( $q, $limits );
3421 foreach ( $this->posts as $post ) {
3422 $r[ (int) $post->ID ] = (int) $post->post_parent;
3427 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3430 * Filter whether to split the query.
3432 * Splitting the query will cause it to fetch just the IDs of the found posts
3433 * (and then individually fetch each post by ID), rather than fetching every
3434 * complete row at once. One massive result vs. many small results.
3438 * @param bool $split_the_query Whether or not to split the query.
3439 * @param WP_Query $this The WP_Query instance.
3441 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3443 if ( $split_the_query ) {
3444 // First get the IDs and then fill in the objects
3446 $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3449 * Filter the Post IDs SQL request before sending.
3453 * @param string $request The post ID request.
3454 * @param WP_Query $this The WP_Query instance.
3456 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3458 $ids = $wpdb->get_col( $this->request );
3461 $this->posts = $ids;
3462 $this->set_found_posts( $q, $limits );
3463 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3465 $this->posts = array();
3468 $this->posts = $wpdb->get_results( $this->request );
3469 $this->set_found_posts( $q, $limits );
3472 // Convert to WP_Post objects
3474 $this->posts = array_map( 'get_post', $this->posts );
3476 if ( ! $q['suppress_filters'] ) {
3478 * Filter the raw post results array, prior to status checks.
3482 * @param array $posts The post results array.
3483 * @param WP_Query &$this The WP_Query instance (passed by reference).
3485 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3488 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3489 /** This filter is documented in wp-includes/query.php */
3490 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3492 /** This filter is documented in wp-includes/query.php */
3493 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3495 /** This filter is documented in wp-includes/query.php */
3496 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3497 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3499 /** This filter is documented in wp-includes/query.php */
3500 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3501 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3503 /** This filter is documented in wp-includes/query.php */
3504 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3506 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3507 $this->comments = $wpdb->get_results($comments_request);
3508 $this->comment_count = count($this->comments);
3511 // Check post status to determine if post should be displayed.
3512 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3513 $status = get_post_status($this->posts[0]);
3514 $post_status_obj = get_post_status_object($status);
3515 //$type = get_post_type($this->posts[0]);
3516 if ( !$post_status_obj->public ) {
3517 if ( ! is_user_logged_in() ) {
3518 // User must be logged in to view unpublished posts.
3519 $this->posts = array();
3521 if ( $post_status_obj->protected ) {
3522 // User must have edit permissions on the draft to preview.
3523 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3524 $this->posts = array();
3526 $this->is_preview = true;
3527 if ( 'future' != $status )
3528 $this->posts[0]->post_date = current_time('mysql');
3530 } elseif ( $post_status_obj->private ) {
3531 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3532 $this->posts = array();
3534 $this->posts = array();
3539 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3541 * Filter the single post for preview mode.
3545 * @param WP_Post $post_preview The Post object.
3546 * @param WP_Query &$this The WP_Query instance (passed by reference).
3548 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3552 // Put sticky posts at the top of the posts array
3553 $sticky_posts = get_option('sticky_posts');
3554 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3555 $num_posts = count($this->posts);
3557 // Loop over posts and relocate stickies to the front.
3558 for ( $i = 0; $i < $num_posts; $i++ ) {
3559 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3560 $sticky_post = $this->posts[$i];
3561 // Remove sticky from current position
3562 array_splice($this->posts, $i, 1);
3563 // Move to front, after other stickies
3564 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3565 // Increment the sticky offset. The next sticky will be placed at this offset.
3567 // Remove post from sticky posts array
3568 $offset = array_search($sticky_post->ID, $sticky_posts);
3569 unset( $sticky_posts[$offset] );
3573 // If any posts have been excluded specifically, Ignore those that are sticky.
3574 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3575 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3577 // Fetch sticky posts that weren't in the query results
3578 if ( !empty($sticky_posts) ) {
3579 $stickies = get_posts( array(
3580 'post__in' => $sticky_posts,
3581 'post_type' => $post_type,
3582 'post_status' => 'publish',
3586 foreach ( $stickies as $sticky_post ) {
3587 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3593 if ( ! $q['suppress_filters'] ) {
3595 * Filter the array of retrieved posts after they've been fetched and
3596 * internally processed.
3600 * @param array $posts The array of retrieved posts.
3601 * @param WP_Query &$this The WP_Query instance (passed by reference).
3603 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3606 // Ensure that any posts added/modified via one of the filters above are
3607 // of the type WP_Post and are filtered.
3608 if ( $this->posts ) {
3609 $this->post_count = count( $this->posts );
3611 $this->posts = array_map( 'get_post', $this->posts );
3613 if ( $q['cache_results'] )
3614 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3616 $this->post = reset( $this->posts );
3618 $this->post_count = 0;
3619 $this->posts = array();
3622 return $this->posts;
3626 * Set up the amount of found posts and the number of pages (if limit clause was used)
3627 * for the current query.
3632 private function set_found_posts( $q, $limits ) {
3635 // Bail if posts is an empty array. Continue if posts is an empty string,
3636 // null, or false to accommodate caching plugins that fill posts later.
3637 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3640 if ( ! empty( $limits ) ) {
3642 * Filter the query to run for retrieving the found posts.
3646 * @param string $found_posts The query to run to find the found posts.
3647 * @param WP_Query &$this The WP_Query instance (passed by reference).
3649 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3651 $this->found_posts = count( $this->posts );
3655 * Filter the number of found posts for the query.
3659 * @param int $found_posts The number of posts found.
3660 * @param WP_Query &$this The WP_Query instance (passed by reference).
3662 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3664 if ( ! empty( $limits ) )
3665 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3669 * Set up the next post and iterate current post index.
3674 * @return WP_Post Next post.
3676 public function next_post() {
3678 $this->current_post++;
3680 $this->post = $this->posts[$this->current_post];
3685 * Sets up the current post.
3687 * Retrieves the next post, sets up the post, sets the 'in the loop'
3693 public function the_post() {
3695 $this->in_the_loop = true;
3697 if ( $this->current_post == -1 ) // loop has just started
3699 * Fires once the loop is started.
3703 * @param WP_Query &$this The WP_Query instance (passed by reference).
3705 do_action_ref_array( 'loop_start', array( &$this ) );
3707 $post = $this->next_post();
3708 $this->setup_postdata( $post );
3712 * Whether there are more posts available in the loop.
3714 * Calls action 'loop_end', when the loop is complete.
3719 * @return bool True if posts are available, false if end of loop.
3721 public function have_posts() {
3722 if ( $this->current_post + 1 < $this->post_count ) {
3724 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3726 * Fires once the loop has ended.
3730 * @param WP_Query &$this The WP_Query instance (passed by reference).
3732 do_action_ref_array( 'loop_end', array( &$this ) );
3733 // Do some cleaning up after the loop
3734 $this->rewind_posts();
3737 $this->in_the_loop = false;
3742 * Rewind the posts and reset post index.
3747 public function rewind_posts() {
3748 $this->current_post = -1;
3749 if ( $this->post_count > 0 ) {
3750 $this->post = $this->posts[0];
3755 * Iterate current comment index and return comment object.
3760 * @return object Comment object.
3762 public function next_comment() {
3763 $this->current_comment++;
3765 $this->comment = $this->comments[$this->current_comment];
3766 return $this->comment;
3770 * Sets up the current comment.
3774 * @global object $comment Current comment.
3776 public function the_comment() {
3779 $comment = $this->next_comment();
3781 if ( $this->current_comment == 0 ) {
3783 * Fires once the comment loop is started.
3787 do_action( 'comment_loop_start' );
3792 * Whether there are more comments available.
3794 * Automatically rewinds comments when finished.
3799 * @return bool True, if more comments. False, if no more posts.
3801 public function have_comments() {
3802 if ( $this->current_comment + 1 < $this->comment_count ) {
3804 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
3805 $this->rewind_comments();
3812 * Rewind the comments, resets the comment index and comment to first.
3817 public function rewind_comments() {
3818 $this->current_comment = -1;
3819 if ( $this->comment_count > 0 ) {
3820 $this->comment = $this->comments[0];
3825 * Sets up the WordPress query by parsing query string.
3830 * @param string $query URL query string.
3831 * @return array List of posts.
3833 public function query( $query ) {
3835 $this->query = $this->query_vars = wp_parse_args( $query );
3836 return $this->get_posts();
3840 * Retrieve queried object.
3842 * If queried object is not set, then the queried object will be set from
3843 * the category, tag, taxonomy, posts page, single post, page, or author
3844 * query variable. After it is set up, it will be returned.
3851 public function get_queried_object() {
3852 if ( isset($this->queried_object) )
3853 return $this->queried_object;
3855 $this->queried_object = null;
3856 $this->queried_object_id = 0;
3858 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
3859 if ( $this->is_category ) {
3860 if ( $this->get( 'cat' ) ) {
3861 $term = get_term( $this->get( 'cat' ), 'category' );
3862 } elseif ( $this->get( 'category_name' ) ) {
3863 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
3865 } elseif ( $this->is_tag ) {
3866 if ( $this->get( 'tag_id' ) ) {
3867 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
3868 } elseif ( $this->get( 'tag' ) ) {
3869 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
3872 // For other tax queries, grab the first term from the first clause.
3873 $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' );
3875 $queried_taxonomies = array_keys( $tax_query_in_and );
3876 $matched_taxonomy = reset( $queried_taxonomies );
3877 $query = $tax_query_in_and[ $matched_taxonomy ];
3879 if ( $query['terms'] ) {
3880 if ( 'term_id' == $query['field'] ) {
3881 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
3883 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
3888 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
3889 $this->queried_object = $term;
3890 $this->queried_object_id = (int) $term->term_id;
3892 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
3893 _make_cat_compat( $this->queried_object );
3895 } elseif ( $this->is_post_type_archive ) {
3896 $post_type = $this->get( 'post_type' );
3897 if ( is_array( $post_type ) )
3898 $post_type = reset( $post_type );
3899 $this->queried_object = get_post_type_object( $post_type );
3900 } elseif ( $this->is_posts_page ) {
3901 $page_for_posts = get_option('page_for_posts');
3902 $this->queried_object = get_post( $page_for_posts );
3903 $this->queried_object_id = (int) $this->queried_object->ID;
3904 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
3905 $this->queried_object = $this->post;
3906 $this->queried_object_id = (int) $this->post->ID;
3907 } elseif ( $this->is_author ) {
3908 $this->queried_object_id = (int) $this->get('author');
3909 $this->queried_object = get_userdata( $this->queried_object_id );
3912 return $this->queried_object;
3916 * Retrieve ID of the current queried object.
3923 public function get_queried_object_id() {
3924 $this->get_queried_object();
3926 if ( isset($this->queried_object_id) ) {
3927 return $this->queried_object_id;
3936 * Sets up the WordPress query, if parameter is not empty.
3941 * @param string $query URL query string.
3944 public function __construct($query = '') {
3945 if ( ! empty($query) ) {
3946 $this->query($query);
3951 * Make private properties readable for backwards compatibility.
3956 * @param string $name Property to get.
3957 * @return mixed Property.
3959 public function __get( $name ) {
3960 return $this->$name;
3964 * Make private properties settable for backwards compatibility.
3969 * @param string $name Property to check if set.
3970 * @return bool Whether the property is set.
3972 public function __isset( $name ) {
3973 return isset( $this->$name );
3977 * Make private properties settable for backwards compatibility.
3982 * @param string $name Property to unset.
3984 public function __unset( $name ) {
3985 unset( $this->$name );
3989 * Make private/protected methods readable for backwards compatibility.
3994 * @param callable $name Method to call.
3995 * @param array $arguments Arguments to pass when calling.
3996 * @return mixed|bool Return value of the callback, otherwise false.
3998 public function __call( $name, $arguments ) {
3999 return call_user_func_array( array( $this, $name ), $arguments );
4003 * Is the query for an existing archive page?
4005 * Month, Year, Category, Author, Post Type archive...
4011 public function is_archive() {
4012 return (bool) $this->is_archive;
4016 * Is the query for an existing post type archive page?
4020 * @param mixed $post_types Optional. Post type or array of posts types to check against.
4023 public function is_post_type_archive( $post_types = '' ) {
4024 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4025 return (bool) $this->is_post_type_archive;
4027 $post_type = $this->get( 'post_type' );
4028 if ( is_array( $post_type ) )
4029 $post_type = reset( $post_type );
4030 $post_type_object = get_post_type_object( $post_type );
4032 return in_array( $post_type_object->name, (array) $post_types );
4036 * Is the query for an existing attachment page?
4040 * @param mixed $attachment Attachment ID, title, slug, or array of such.
4043 public function is_attachment( $attachment = '' ) {
4044 if ( ! $this->is_attachment ) {
4048 if ( empty( $attachment ) ) {
4052 $attachment = (array) $attachment;
4054 $post_obj = $this->get_queried_object();
4056 if ( in_array( $post_obj->ID, $attachment ) ) {
4058 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4060 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4067 * Is the query for an existing author archive page?
4069 * If the $author parameter is specified, this function will additionally
4070 * check if the query is for one of the authors specified.
4074 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4077 public function is_author( $author = '' ) {
4078 if ( !$this->is_author )
4081 if ( empty($author) )
4084 $author_obj = $this->get_queried_object();
4086 $author = (array) $author;
4088 if ( in_array( $author_obj->ID, $author ) )
4090 elseif ( in_array( $author_obj->nickname, $author ) )
4092 elseif ( in_array( $author_obj->user_nicename, $author ) )
4099 * Is the query for an existing category archive page?
4101 * If the $category parameter is specified, this function will additionally
4102 * check if the query is for one of the categories specified.
4106 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4109 public function is_category( $category = '' ) {
4110 if ( !$this->is_category )
4113 if ( empty($category) )
4116 $cat_obj = $this->get_queried_object();
4118 $category = (array) $category;
4120 if ( in_array( $cat_obj->term_id, $category ) )
4122 elseif ( in_array( $cat_obj->name, $category ) )
4124 elseif ( in_array( $cat_obj->slug, $category ) )
4131 * Is the query for an existing tag archive page?
4133 * If the $tag parameter is specified, this function will additionally
4134 * check if the query is for one of the tags specified.
4138 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4141 public function is_tag( $tag = '' ) {
4142 if ( ! $this->is_tag )
4145 if ( empty( $tag ) )
4148 $tag_obj = $this->get_queried_object();
4150 $tag = (array) $tag;
4152 if ( in_array( $tag_obj->term_id, $tag ) )
4154 elseif ( in_array( $tag_obj->name, $tag ) )
4156 elseif ( in_array( $tag_obj->slug, $tag ) )
4163 * Is the query for an existing taxonomy archive page?
4165 * If the $taxonomy parameter is specified, this function will additionally
4166 * check if the query is for that specific $taxonomy.
4168 * If the $term parameter is specified in addition to the $taxonomy parameter,
4169 * this function will additionally check if the query is for one of the terms
4174 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4175 * @param mixed $term. Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4178 public function is_tax( $taxonomy = '', $term = '' ) {
4179 global $wp_taxonomies;
4181 if ( !$this->is_tax )
4184 if ( empty( $taxonomy ) )
4187 $queried_object = $this->get_queried_object();
4188 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4189 $term_array = (array) $term;
4191 // Check that the taxonomy matches.
4192 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4195 // Only a Taxonomy provided.
4196 if ( empty( $term ) )
4199 return isset( $queried_object->term_id ) &&
4200 count( array_intersect(
4201 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4207 * Whether the current URL is within the comments popup window.
4213 public function is_comments_popup() {
4214 return (bool) $this->is_comments_popup;
4218 * Is the query for an existing date archive?
4224 public function is_date() {
4225 return (bool) $this->is_date;
4229 * Is the query for an existing day archive?
4235 public function is_day() {
4236 return (bool) $this->is_day;
4240 * Is the query for a feed?
4244 * @param string|array $feeds Optional feed types to check.
4247 public function is_feed( $feeds = '' ) {
4248 if ( empty( $feeds ) || ! $this->is_feed )
4249 return (bool) $this->is_feed;
4250 $qv = $this->get( 'feed' );
4251 if ( 'feed' == $qv )
4252 $qv = get_default_feed();
4253 return in_array( $qv, (array) $feeds );
4257 * Is the query for a comments feed?
4263 public function is_comment_feed() {
4264 return (bool) $this->is_comment_feed;
4268 * Is the query for the front page of the site?
4270 * This is for what is displayed at your site's main URL.
4272 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4274 * If you set a static page for the front page of your site, this function will return
4275 * true when viewing that page.
4277 * Otherwise the same as @see WP_Query::is_home()
4281 * @return bool True, if front of site.
4283 public function is_front_page() {
4285 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4287 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4294 * Is the query for the blog homepage?
4296 * This is the page which shows the time based blog content of your site.
4298 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4300 * If you set a static page for the front page of your site, this function will return
4301 * true only on the page you set as the "Posts page".
4303 * @see WP_Query::is_front_page()
4307 * @return bool True if blog view homepage.
4309 public function is_home() {
4310 return (bool) $this->is_home;
4314 * Is the query for an existing month archive?
4320 public function is_month() {
4321 return (bool) $this->is_month;
4325 * Is the query for an existing single page?
4327 * If the $page parameter is specified, this function will additionally
4328 * check if the query is for one of the pages specified.
4330 * @see WP_Query::is_single()
4331 * @see WP_Query::is_singular()
4335 * @param mixed $page Page ID, title, slug, path, or array of such.
4338 public function is_page( $page = '' ) {
4339 if ( !$this->is_page )
4342 if ( empty( $page ) )
4345 $page_obj = $this->get_queried_object();
4347 $page = (array) $page;
4349 if ( in_array( $page_obj->ID, $page ) ) {
4351 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4353 } else if ( in_array( $page_obj->post_name, $page ) ) {
4356 foreach ( $page as $pagepath ) {
4357 if ( ! strpos( $pagepath, '/' ) ) {
4360 $pagepath_obj = get_page_by_path( $pagepath );
4362 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4372 * Is the query for paged result and not for the first page?
4378 public function is_paged() {
4379 return (bool) $this->is_paged;
4383 * Is the query for a post or page preview?
4389 public function is_preview() {
4390 return (bool) $this->is_preview;
4394 * Is the query for the robots file?
4400 public function is_robots() {
4401 return (bool) $this->is_robots;
4405 * Is the query for a search?
4411 public function is_search() {
4412 return (bool) $this->is_search;
4416 * Is the query for an existing single post?
4418 * Works for any post type, except attachments and pages
4420 * If the $post parameter is specified, this function will additionally
4421 * check if the query is for one of the Posts specified.
4423 * @see WP_Query::is_page()
4424 * @see WP_Query::is_singular()
4428 * @param mixed $post Post ID, title, slug, path, or array of such.
4431 public function is_single( $post = '' ) {
4432 if ( !$this->is_single )
4438 $post_obj = $this->get_queried_object();
4440 $post = (array) $post;
4442 if ( in_array( $post_obj->ID, $post ) ) {
4444 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4446 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4449 foreach ( $post as $postpath ) {
4450 if ( ! strpos( $postpath, '/' ) ) {
4453 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4455 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4464 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4466 * If the $post_types parameter is specified, this function will additionally
4467 * check if the query is for one of the Posts Types specified.
4469 * @see WP_Query::is_page()
4470 * @see WP_Query::is_single()
4474 * @param mixed $post_types Optional. Post Type or array of Post Types
4477 public function is_singular( $post_types = '' ) {
4478 if ( empty( $post_types ) || !$this->is_singular )
4479 return (bool) $this->is_singular;
4481 $post_obj = $this->get_queried_object();
4483 return in_array( $post_obj->post_type, (array) $post_types );
4487 * Is the query for a specific time?
4493 public function is_time() {
4494 return (bool) $this->is_time;
4498 * Is the query for a trackback endpoint call?
4504 public function is_trackback() {
4505 return (bool) $this->is_trackback;
4509 * Is the query for an existing year archive?
4515 public function is_year() {
4516 return (bool) $this->is_year;
4520 * Is the query a 404 (returns no results)?
4526 public function is_404() {
4527 return (bool) $this->is_404;
4531 * Is the query the main query?
4537 public function is_main_query() {
4538 global $wp_the_query;
4539 return $wp_the_query === $this;
4543 * Set up global post data.
4547 * @param WP_Post $post Post data.
4548 * @return bool True when finished.
4550 public function setup_postdata( $post ) {
4551 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4553 $id = (int) $post->ID;
4555 $authordata = get_userdata($post->post_author);
4557 $currentday = mysql2date('d.m.y', $post->post_date, false);
4558 $currentmonth = mysql2date('m', $post->post_date, false);
4561 $page = $this->get( 'page' );
4566 * Force full post content when viewing the permalink for the $post,
4567 * or when on an RSS feed. Otherwise respect the 'more' tag.
4569 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4571 } else if ( $this->is_feed() ) {
4577 $content = $post->post_content;
4578 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4581 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4582 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4583 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4585 // Ignore nextpage at the beginning of the content.
4586 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4587 $content = substr( $content, 15 );
4589 $pages = explode('<!--nextpage-->', $content);
4590 $numpages = count($pages);
4591 if ( $numpages > 1 )
4594 $pages = array( $post->post_content );
4598 * Fires once the post data has been setup.
4601 * @since 4.1.0 Introduced `$this` parameter.
4603 * @param WP_Post &$post The Post object (passed by reference).
4604 * @param WP_Query &$this The current Query object (passed by reference).
4606 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4611 * After looping through a nested query, this function
4612 * restores the $post global to the current post in this query.
4616 public function reset_postdata() {
4617 if ( ! empty( $this->post ) ) {
4618 $GLOBALS['post'] = $this->post;
4619 setup_postdata( $this->post );
4625 * Redirect old slugs to the correct permalink.
4627 * Attempts to find the current slug from the past slugs.
4632 * @global wpdb $wpdb WordPress database abstraction object.
4634 * @return null If no link is found, null is returned.
4636 function wp_old_slug_redirect() {
4638 if ( is_404() && '' != $wp_query->query_vars['name'] ) :
4641 // Guess the current post_type based on the query vars.
4642 if ( get_query_var('post_type') )
4643 $post_type = get_query_var('post_type');
4644 elseif ( !empty($wp_query->query_vars['pagename']) )
4645 $post_type = 'page';
4647 $post_type = 'post';
4649 if ( is_array( $post_type ) ) {
4650 if ( count( $post_type ) > 1 )
4652 $post_type = array_shift( $post_type );
4655 // Do not attempt redirect for hierarchical post types
4656 if ( is_post_type_hierarchical( $post_type ) )
4659 $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']);
4661 // if year, monthnum, or day have been specified, make our query more precise
4662 // just in case there are multiple identical _wp_old_slug values
4663 if ( '' != $wp_query->query_vars['year'] )
4664 $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
4665 if ( '' != $wp_query->query_vars['monthnum'] )
4666 $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
4667 if ( '' != $wp_query->query_vars['day'] )
4668 $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
4670 $id = (int) $wpdb->get_var($query);
4675 $link = get_permalink($id);
4680 wp_redirect( $link, 301 ); // Permanent redirect
4686 * Set up global post data.
4690 * @param object $post Post data.
4691 * @return bool True when finished.
4693 function setup_postdata( $post ) {
4696 if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
4697 return $wp_query->setup_postdata( $post );