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' ] : '';