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 mixed $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 mixed $taxonomy Optional. Taxonomy slug or slugs.
280 * @param mixed $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()
412 * @return bool True, if front of site.
414 function is_front_page() {
417 if ( ! isset( $wp_query ) ) {
418 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
422 return $wp_query->is_front_page();
426 * Is the query for the blog homepage?
428 * This is the page which shows the time based blog content of your site.
430 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
432 * If you set a static page for the front page of your site, this function will return
433 * true only on the page you set as the "Posts page".
435 * @see is_front_page()
437 * @see WP_Query::is_home()
441 * @return bool True if blog view homepage.
446 if ( ! isset( $wp_query ) ) {
447 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
451 return $wp_query->is_home();
455 * Is the query for an existing month archive?
457 * @see WP_Query::is_month()
463 function is_month() {
466 if ( ! isset( $wp_query ) ) {
467 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
471 return $wp_query->is_month();
475 * Is the query for an existing single page?
477 * If the $page parameter is specified, this function will additionally
478 * check if the query is for one of the pages specified.
483 * @see WP_Query::is_page()
487 * @param mixed $page Page ID, title, slug, or array of such.
490 function is_page( $page = '' ) {
493 if ( ! isset( $wp_query ) ) {
494 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
498 return $wp_query->is_page( $page );
502 * Is the query for paged result and not for the first page?
504 * @see WP_Query::is_paged()
510 function is_paged() {
513 if ( ! isset( $wp_query ) ) {
514 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
518 return $wp_query->is_paged();
522 * Is the query for a post or page preview?
524 * @see WP_Query::is_preview()
530 function is_preview() {
533 if ( ! isset( $wp_query ) ) {
534 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
538 return $wp_query->is_preview();
542 * Is the query for the robots file?
544 * @see WP_Query::is_robots()
550 function is_robots() {
553 if ( ! isset( $wp_query ) ) {
554 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
558 return $wp_query->is_robots();
562 * Is the query for a search?
564 * @see WP_Query::is_search()
570 function is_search() {
573 if ( ! isset( $wp_query ) ) {
574 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
578 return $wp_query->is_search();
582 * Is the query for an existing single post?
584 * Works for any post type, except attachments and pages
586 * If the $post parameter is specified, this function will additionally
587 * check if the query is for one of the Posts specified.
592 * @see WP_Query::is_single()
596 * @param mixed $post Post ID, title, slug, or array of such.
599 function is_single( $post = '' ) {
602 if ( ! isset( $wp_query ) ) {
603 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
607 return $wp_query->is_single( $post );
611 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
613 * If the $post_types parameter is specified, this function will additionally
614 * check if the query is for one of the Posts Types specified.
619 * @see WP_Query::is_singular()
623 * @param mixed $post_types Optional. Post Type or array of Post Types
626 function is_singular( $post_types = '' ) {
629 if ( ! isset( $wp_query ) ) {
630 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
634 return $wp_query->is_singular( $post_types );
638 * Is the query for a specific time?
640 * @see WP_Query::is_time()
649 if ( ! isset( $wp_query ) ) {
650 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
654 return $wp_query->is_time();
658 * Is the query for a trackback endpoint call?
660 * @see WP_Query::is_trackback()
666 function is_trackback() {
669 if ( ! isset( $wp_query ) ) {
670 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
674 return $wp_query->is_trackback();
678 * Is the query for an existing year archive?
680 * @see WP_Query::is_year()
689 if ( ! isset( $wp_query ) ) {
690 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
694 return $wp_query->is_year();
698 * Is the query a 404 (returns no results)?
700 * @see WP_Query::is_404()
709 if ( ! isset( $wp_query ) ) {
710 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
714 return $wp_query->is_404();
718 * Is the query the main query?
724 function is_main_query() {
725 if ( 'pre_get_posts' === current_filter() ) {
726 $message = sprintf( __( 'In <code>%1$s</code>, use the <code>%2$s</code> method, not the <code>%3$s</code> function. See %4$s.' ),
727 'pre_get_posts', 'WP_Query::is_main_query()', 'is_main_query()', __( 'http://codex.wordpress.org/Function_Reference/is_main_query' ) );
728 _doing_it_wrong( __FUNCTION__, $message, '3.7' );
732 return $wp_query->is_main_query();
736 * The Loop. Post loop control.
740 * Whether current WordPress query has results to loop over.
742 * @see WP_Query::have_posts()
748 function have_posts() {
751 return $wp_query->have_posts();
755 * Whether the caller is in the Loop.
760 * @return bool True if caller is within loop, false if loop hasn't started or ended.
762 function in_the_loop() {
765 return $wp_query->in_the_loop;
769 * Rewind the loop posts.
771 * @see WP_Query::rewind_posts()
777 function rewind_posts() {
780 return $wp_query->rewind_posts();
784 * Iterate the post index in the loop.
786 * @see WP_Query::the_post()
790 function the_post() {
793 $wp_query->the_post();
801 * Whether there are comments to loop over.
803 * @see WP_Query::have_comments()
809 function have_comments() {
811 return $wp_query->have_comments();
815 * Iterate comment index in the comment loop.
817 * @see WP_Query::the_comment()
823 function the_comment() {
825 return $wp_query->the_comment();
833 * The WordPress Query class.
835 * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
842 * Query vars set by the user
851 * Query vars, after parsing
857 public $query_vars = array();
860 * Taxonomy query, as passed to get_tax_sql()
864 * @var object WP_Tax_Query
869 * Metadata query container
873 * @var object WP_Meta_Query
875 public $meta_query = false;
878 * Date query container
882 * @var object WP_Date_Query
884 public $date_query = false;
887 * Holds the data for a single object that is queried.
889 * Holds the contents of a post, page, category, attachment.
895 public $queried_object;
898 * The ID of the queried object.
904 public $queried_object_id;
907 * Get post database query.
925 * The amount of posts for the current query.
931 public $post_count = 0;
934 * Index of the current item in the loop.
940 public $current_post = -1;
943 * Whether the loop has started and the caller is in the loop.
949 public $in_the_loop = false;
961 * The list of comments for current post.
970 * The amount of comments for the posts.
976 public $comment_count = 0;
979 * The index of the comment in the comment loop.
985 public $current_comment = -1;
988 * Current comment ID.
997 * The amount of found posts for the current query.
999 * If limit clause was not used, equals $post_count.
1005 public $found_posts = 0;
1008 * The amount of pages.
1014 public $max_num_pages = 0;
1017 * The amount of comment pages.
1023 public $max_num_comment_pages = 0;
1026 * Set if query is single post.
1032 public $is_single = false;
1035 * Set if query is preview of blog.
1041 public $is_preview = false;
1044 * Set if query returns a page.
1050 public $is_page = false;
1053 * Set if query is an archive list.
1059 public $is_archive = false;
1062 * Set if query is part of a date.
1068 public $is_date = false;
1071 * Set if query contains a year.
1077 public $is_year = false;
1080 * Set if query contains a month.
1086 public $is_month = false;
1089 * Set if query contains a day.
1095 public $is_day = false;
1098 * Set if query contains time.
1104 public $is_time = false;
1107 * Set if query contains an author.
1113 public $is_author = false;
1116 * Set if query contains category.
1122 public $is_category = false;
1125 * Set if query contains tag.
1131 public $is_tag = false;
1134 * Set if query contains taxonomy.
1140 public $is_tax = false;
1143 * Set if query was part of a search result.
1149 public $is_search = false;
1152 * Set if query is feed display.
1158 public $is_feed = false;
1161 * Set if query is comment feed display.
1167 public $is_comment_feed = false;
1170 * Set if query is trackback.
1176 public $is_trackback = false;
1179 * Set if query is blog homepage.
1185 public $is_home = false;
1188 * Set if query couldn't found anything.
1194 public $is_404 = false;
1197 * Set if query is within comments popup window.
1203 public $is_comments_popup = false;
1206 * Set if query is paged
1212 public $is_paged = false;
1215 * Set if query is part of administration page.
1221 public $is_admin = false;
1224 * Set if query is an attachment.
1230 public $is_attachment = false;
1233 * Set if is single, is a page, or is an attachment.
1239 public $is_singular = false;
1242 * Set if query is for robots.
1248 public $is_robots = false;
1251 * Set if query contains posts.
1253 * Basically, the homepage if the option isn't set for the static homepage.
1259 public $is_posts_page = false;
1262 * Set if query is for a post type archive.
1268 public $is_post_type_archive = false;
1271 * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
1272 * whether we have to re-parse because something has changed
1277 private $query_vars_hash = false;
1280 * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
1281 * via pre_get_posts hooks.
1286 private $query_vars_changed = true;
1289 * Set if post thumbnails are cached
1295 public $thumbnails_cached = false;
1298 * Cached list of search stopwords.
1306 * Resets query flags to false.
1308 * The query flags are what page info WordPress was able to figure out.
1313 private function init_query_flags() {
1314 $this->is_single = false;
1315 $this->is_preview = false;
1316 $this->is_page = false;
1317 $this->is_archive = false;
1318 $this->is_date = false;
1319 $this->is_year = false;
1320 $this->is_month = false;
1321 $this->is_day = false;
1322 $this->is_time = false;
1323 $this->is_author = false;
1324 $this->is_category = false;
1325 $this->is_tag = false;
1326 $this->is_tax = false;
1327 $this->is_search = false;
1328 $this->is_feed = false;
1329 $this->is_comment_feed = false;
1330 $this->is_trackback = false;
1331 $this->is_home = false;
1332 $this->is_404 = false;
1333 $this->is_comments_popup = false;
1334 $this->is_paged = false;
1335 $this->is_admin = false;
1336 $this->is_attachment = false;
1337 $this->is_singular = false;
1338 $this->is_robots = false;
1339 $this->is_posts_page = false;
1340 $this->is_post_type_archive = false;
1344 * Initiates object properties and sets default values.
1349 public function init() {
1350 unset($this->posts);
1351 unset($this->query);
1352 $this->query_vars = array();
1353 unset($this->queried_object);
1354 unset($this->queried_object_id);
1355 $this->post_count = 0;
1356 $this->current_post = -1;
1357 $this->in_the_loop = false;
1358 unset( $this->request );
1359 unset( $this->post );
1360 unset( $this->comments );
1361 unset( $this->comment );
1362 $this->comment_count = 0;
1363 $this->current_comment = -1;
1364 $this->found_posts = 0;
1365 $this->max_num_pages = 0;
1366 $this->max_num_comment_pages = 0;
1368 $this->init_query_flags();
1372 * Reparse the query vars.
1377 public function parse_query_vars() {
1378 $this->parse_query();
1382 * Fills in the query variables, which do not exist within the parameter.
1387 * @param array $array Defined query variables.
1388 * @return array Complete query variables with undefined ones filled in empty.
1390 public function fill_query_vars($array) {
1430 foreach ( $keys as $key ) {
1431 if ( !isset($array[$key]) )
1435 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in',
1436 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
1437 'author__in', 'author__not_in' );
1439 foreach ( $array_keys as $key ) {
1440 if ( !isset($array[$key]) )
1441 $array[$key] = array();
1447 * Parse a query string and set query type booleans.
1452 * @param string|array $query {
1453 * Optional. Array or string of Query parameters.
1455 * @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
1456 * @type int|string $author Author ID, or comma-separated list of IDs.
1457 * @type string $author_name User 'user_nicename'.
1458 * @type array $author__in An array of author IDs to query from.
1459 * @type array $author__not_in An array of author IDs not to query from.
1460 * @type bool $cache_results Whether to cache post information. Default true.
1461 * @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
1462 * @type array $category__and An array of category IDs (AND in).
1463 * @type array $category__in An array of category IDs (OR in, no children).
1464 * @type array $category__not_in An array of category IDs (NOT in).
1465 * @type string $category_name Use category slug (not name, this or any children).
1466 * @type int $comments_per_page The number of comments to return per page.
1467 * Default 'comments_per_page' option.
1468 * @type int|string $comments_popup Whether the query is within the comments popup. Default empty.
1469 * @type array $date_query An associative array of WP_Date_Query arguments.
1470 * {@see WP_Date_Query::__construct()}
1471 * @type int $day Day of the month. Default empty. Accepts numbers 1-31.
1472 * @type bool $exact Whether to search by exact keyword. Default false.
1473 * @type string|array $fields Which fields to return. Single field or all fields (string),
1474 * or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
1475 * Default all fields. Accepts 'ids', 'id=>parent'.
1476 * @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
1477 * @type bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
1478 * excludes stickies from 'post__in'. Accepts 1|true, 0|false.
1480 * @type int $m Combination YearMonth. Accepts any four-digit year and month
1481 * numbers 1-12. Default empty.
1482 * @type string $meta_compare Comparison operator to test the 'meta_value'.
1483 * @type string $meta_key Custom field key.
1484 * @type array $meta_query An associative array of WP_Meta_Query arguments.
1485 * {@see WP_Meta_Query->queries}
1486 * @type string $meta_value Custom field value.
1487 * @type int $meta_value_num Custom field value number.
1488 * @type int $menu_order The menu order of the posts.
1489 * @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
1490 * @type string $name Post slug.
1491 * @type bool $nopaging Show all posts (true) or paginate (false). Default false.
1492 * @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
1493 * performance. Default false.
1494 * @type int $offset The number of posts to offset before retrieval.
1495 * @type string $order Designates ascending or descending order of posts. Default 'DESC'.
1496 * Accepts 'ASC', 'DESC'.
1497 * @type string $orderby Sort retrieved posts by parameter. One or more options can be
1498 * passed. To use 'meta_value', or 'meta_value_num',
1499 * 'meta_key=keyname' must be also be defined. Default 'date'.
1500 * Accepts 'none', 'name', 'author', 'date', 'title', 'modified',
1501 * 'menu_order', 'parent', 'ID', 'rand', 'comment_count'.
1502 * @type int $p Post ID.
1503 * @type int $page Show the number of posts that would show up on page X of a
1504 * static front page.
1505 * @type int $paged The number of the current page.
1506 * @type int $page_id Page ID.
1507 * @type string $pagename Page slug.
1508 * @type string $perm Show posts if user has the appropriate capability.
1509 * @type array $post__in An array of post IDs to retrieve, sticky posts will be included
1510 * @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
1511 * @type array $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
1512 * separated IDs will NOT work.
1513 * @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
1515 * @type array $post_parent__in An array containing parent page IDs to query child pages from.
1516 * @type array $post_parent__not_in An array containing parent page IDs not to query child pages from.
1517 * @type string|array $post_type A post type slug (string) or array of post type slugs.
1518 * Default 'any' if using 'tax_query'.
1519 * @type string|array $post_status A post status (string) or array of post statuses.
1520 * @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
1521 * @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
1522 * 'posts_per_page' when is_archive(), or is_search() are true.
1523 * @type string $s Search keyword.
1524 * @type int $second Second of the minute. Default empty. Accepts numbers 0-60.
1525 * @type array $search_terms Array of search terms.
1526 * @type bool $sentence Whether to search by phrase. Default false.
1527 * @type bool $suppress_filters Whether to suppress filters. Default false.
1528 * @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
1529 * @type array $tag__and An array of tag ids (AND in).
1530 * @type array $tag__in An array of tag ids (OR in).
1531 * @type array $tag__not_in An array of tag ids (NOT in).
1532 * @type int $tag_id Tag id or comma-separated list of IDs.
1533 * @type array $tag_slug__and An array of tag slugs (AND in).
1534 * @type array $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
1535 * true. Note: a string of comma-separated IDs will NOT work.
1536 * @type array $tax_query An associative array of WP_Tax_Query arguments.
1537 * {@see WP_Tax_Query->queries}
1538 * @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
1539 * @type bool $update_post_term_cache Whether to update the post term cache. Default true.
1540 * @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
1541 * @type int $year The four-digit year. Default empty. Accepts any four-digit year.
1544 public function parse_query( $query = '' ) {
1545 if ( ! empty( $query ) ) {
1547 $this->query = $this->query_vars = wp_parse_args( $query );
1548 } elseif ( ! isset( $this->query ) ) {
1549 $this->query = $this->query_vars;
1552 $this->query_vars = $this->fill_query_vars($this->query_vars);
1553 $qv = &$this->query_vars;
1554 $this->query_vars_changed = true;
1556 if ( ! empty($qv['robots']) )
1557 $this->is_robots = true;
1559 $qv['p'] = absint($qv['p']);
1560 $qv['page_id'] = absint($qv['page_id']);
1561 $qv['year'] = absint($qv['year']);
1562 $qv['monthnum'] = absint($qv['monthnum']);
1563 $qv['day'] = absint($qv['day']);
1564 $qv['w'] = absint($qv['w']);
1565 $qv['m'] = preg_replace( '|[^0-9]|', '', $qv['m'] );
1566 $qv['paged'] = absint($qv['paged']);
1567 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1568 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
1569 $qv['pagename'] = trim( $qv['pagename'] );
1570 $qv['name'] = trim( $qv['name'] );
1571 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1572 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1573 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1574 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
1576 // Fairly insane upper bound for search string lengths.
1577 if ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 )
1580 // Compat. Map subpost to attachment.
1581 if ( '' != $qv['subpost'] )
1582 $qv['attachment'] = $qv['subpost'];
1583 if ( '' != $qv['subpost_id'] )
1584 $qv['attachment_id'] = $qv['subpost_id'];
1586 $qv['attachment_id'] = absint($qv['attachment_id']);
1588 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1589 $this->is_single = true;
1590 $this->is_attachment = true;
1591 } elseif ( '' != $qv['name'] ) {
1592 $this->is_single = true;
1593 } elseif ( $qv['p'] ) {
1594 $this->is_single = true;
1595 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1596 // If year, month, day, hour, minute, and second are set, a single
1597 // post is being queried.
1598 $this->is_single = true;
1599 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1600 $this->is_page = true;
1601 $this->is_single = false;
1603 // Look for archive queries. Dates, categories, authors, search, post type archives.
1605 if ( isset( $this->query['s'] ) ) {
1606 $this->is_search = true;
1609 if ( '' !== $qv['second'] ) {
1610 $this->is_time = true;
1611 $this->is_date = true;
1614 if ( '' !== $qv['minute'] ) {
1615 $this->is_time = true;
1616 $this->is_date = true;
1619 if ( '' !== $qv['hour'] ) {
1620 $this->is_time = true;
1621 $this->is_date = true;
1625 if ( ! $this->is_date ) {
1626 $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
1627 if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
1628 $qv['error'] = '404';
1630 $this->is_day = true;
1631 $this->is_date = true;
1636 if ( $qv['monthnum'] ) {
1637 if ( ! $this->is_date ) {
1638 if ( 12 < $qv['monthnum'] ) {
1639 $qv['error'] = '404';
1641 $this->is_month = true;
1642 $this->is_date = true;
1647 if ( $qv['year'] ) {
1648 if ( ! $this->is_date ) {
1649 $this->is_year = true;
1650 $this->is_date = true;
1655 $this->is_date = true;
1656 if ( strlen($qv['m']) > 9 ) {
1657 $this->is_time = true;
1658 } else if ( strlen($qv['m']) > 7 ) {
1659 $this->is_day = true;
1660 } else if ( strlen($qv['m']) > 5 ) {
1661 $this->is_month = true;
1663 $this->is_year = true;
1667 if ( '' != $qv['w'] ) {
1668 $this->is_date = true;
1671 $this->query_vars_hash = false;
1672 $this->parse_tax_query( $qv );
1674 foreach ( $this->tax_query->queries as $tax_query ) {
1675 if ( 'NOT IN' != $tax_query['operator'] ) {
1676 switch ( $tax_query['taxonomy'] ) {
1678 $this->is_category = true;
1681 $this->is_tag = true;
1684 $this->is_tax = true;
1688 unset( $tax_query );
1690 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1691 $this->is_author = false;
1693 $this->is_author = true;
1696 if ( '' != $qv['author_name'] )
1697 $this->is_author = true;
1699 if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
1700 $post_type_obj = get_post_type_object( $qv['post_type'] );
1701 if ( ! empty( $post_type_obj->has_archive ) )
1702 $this->is_post_type_archive = true;
1705 if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
1706 $this->is_archive = true;
1709 if ( '' != $qv['feed'] )
1710 $this->is_feed = true;
1712 if ( '' != $qv['tb'] )
1713 $this->is_trackback = true;
1715 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
1716 $this->is_paged = true;
1718 if ( '' != $qv['comments_popup'] )
1719 $this->is_comments_popup = true;
1721 // if we're previewing inside the write screen
1722 if ( '' != $qv['preview'] )
1723 $this->is_preview = true;
1726 $this->is_admin = true;
1728 if ( false !== strpos($qv['feed'], 'comments-') ) {
1729 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1730 $qv['withcomments'] = 1;
1733 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1735 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1736 $this->is_comment_feed = true;
1738 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 ) )
1739 $this->is_home = true;
1741 // Correct is_* for page_on_front and page_for_posts
1742 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1743 $_query = wp_parse_args($this->query);
1744 // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
1745 if ( isset($_query['pagename']) && '' == $_query['pagename'] )
1746 unset($_query['pagename']);
1747 if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
1748 $this->is_page = true;
1749 $this->is_home = false;
1750 $qv['page_id'] = get_option('page_on_front');
1751 // Correct <!--nextpage--> for page_on_front
1752 if ( !empty($qv['paged']) ) {
1753 $qv['page'] = $qv['paged'];
1754 unset($qv['paged']);
1759 if ( '' != $qv['pagename'] ) {
1760 $this->queried_object = get_page_by_path($qv['pagename']);
1761 if ( !empty($this->queried_object) )
1762 $this->queried_object_id = (int) $this->queried_object->ID;
1764 unset($this->queried_object);
1766 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1767 $this->is_page = false;
1768 $this->is_home = true;
1769 $this->is_posts_page = true;
1773 if ( $qv['page_id'] ) {
1774 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1775 $this->is_page = false;
1776 $this->is_home = true;
1777 $this->is_posts_page = true;
1781 if ( !empty($qv['post_type']) ) {
1782 if ( is_array($qv['post_type']) )
1783 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1785 $qv['post_type'] = sanitize_key($qv['post_type']);
1788 if ( ! empty( $qv['post_status'] ) ) {
1789 if ( is_array( $qv['post_status'] ) )
1790 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1792 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1795 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1796 $this->is_comment_feed = false;
1798 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1799 // Done correcting is_* for page_on_front and page_for_posts
1801 if ( '404' == $qv['error'] )
1804 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1805 $this->query_vars_changed = false;
1808 * Fires after the main query vars have been parsed.
1812 * @param WP_Query &$this The WP_Query instance (passed by reference).
1814 do_action_ref_array( 'parse_query', array( &$this ) );
1818 * Parses various taxonomy related query vars.
1820 * For BC, this method is not marked as protected. See [28987].
1825 * @param array &$q The query variables
1827 function parse_tax_query( &$q ) {
1828 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1829 $tax_query = $q['tax_query'];
1831 $tax_query = array();
1834 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1835 $tax_query[] = array(
1836 'taxonomy' => $q['taxonomy'],
1837 'terms' => array( $q['term'] ),
1842 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1843 if ( 'post_tag' == $taxonomy )
1844 continue; // Handled further down in the $q['tag'] block
1846 if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1847 $tax_query_defaults = array(
1848 'taxonomy' => $taxonomy,
1852 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1853 $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1856 $term = $q[$t->query_var];
1858 if ( strpos($term, '+') !== false ) {
1859 $terms = preg_split( '/[+]+/', $term );
1860 foreach ( $terms as $term ) {
1861 $tax_query[] = array_merge( $tax_query_defaults, array(
1862 'terms' => array( $term )
1866 $tax_query[] = array_merge( $tax_query_defaults, array(
1867 'terms' => preg_split( '/[,]+/', $term )
1874 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1875 $cat_in = $cat_not_in = array();
1877 $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1878 $cat_array = array_map( 'intval', $cat_array );
1879 $q['cat'] = implode( ',', $cat_array );
1881 foreach ( $cat_array as $cat ) {
1885 $cat_not_in[] = abs( $cat );
1888 if ( ! empty( $cat_in ) ) {
1889 $tax_query[] = array(
1890 'taxonomy' => 'category',
1892 'field' => 'term_id',
1893 'include_children' => true
1897 if ( ! empty( $cat_not_in ) ) {
1898 $tax_query[] = array(
1899 'taxonomy' => 'category',
1900 'terms' => $cat_not_in,
1901 'field' => 'term_id',
1902 'operator' => 'NOT IN',
1903 'include_children' => true
1906 unset( $cat_array, $cat_in, $cat_not_in );
1909 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1910 $q['category__and'] = (array) $q['category__and'];
1911 if ( ! isset( $q['category__in'] ) )
1912 $q['category__in'] = array();
1913 $q['category__in'][] = absint( reset( $q['category__and'] ) );
1914 unset( $q['category__and'] );
1917 if ( ! empty( $q['category__in'] ) ) {
1918 $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1919 $tax_query[] = array(
1920 'taxonomy' => 'category',
1921 'terms' => $q['category__in'],
1922 'field' => 'term_id',
1923 'include_children' => false
1927 if ( ! empty($q['category__not_in']) ) {
1928 $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
1929 $tax_query[] = array(
1930 'taxonomy' => 'category',
1931 'terms' => $q['category__not_in'],
1932 'operator' => 'NOT IN',
1933 'include_children' => false
1937 if ( ! empty($q['category__and']) ) {
1938 $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
1939 $tax_query[] = array(
1940 'taxonomy' => 'category',
1941 'terms' => $q['category__and'],
1942 'field' => 'term_id',
1943 'operator' => 'AND',
1944 'include_children' => false
1949 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
1950 if ( strpos($q['tag'], ',') !== false ) {
1951 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
1952 foreach ( (array) $tags as $tag ) {
1953 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1954 $q['tag_slug__in'][] = $tag;
1956 } else if ( preg_match('/[+\r\n\t ]+/', $q['tag']) || !empty($q['cat']) ) {
1957 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
1958 foreach ( (array) $tags as $tag ) {
1959 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1960 $q['tag_slug__and'][] = $tag;
1963 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1964 $q['tag_slug__in'][] = $q['tag'];
1968 if ( !empty($q['tag_id']) ) {
1969 $q['tag_id'] = absint( $q['tag_id'] );
1970 $tax_query[] = array(
1971 'taxonomy' => 'post_tag',
1972 'terms' => $q['tag_id']
1976 if ( !empty($q['tag__in']) ) {
1977 $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
1978 $tax_query[] = array(
1979 'taxonomy' => 'post_tag',
1980 'terms' => $q['tag__in']
1984 if ( !empty($q['tag__not_in']) ) {
1985 $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
1986 $tax_query[] = array(
1987 'taxonomy' => 'post_tag',
1988 'terms' => $q['tag__not_in'],
1989 'operator' => 'NOT IN'
1993 if ( !empty($q['tag__and']) ) {
1994 $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
1995 $tax_query[] = array(
1996 'taxonomy' => 'post_tag',
1997 'terms' => $q['tag__and'],
2002 if ( !empty($q['tag_slug__in']) ) {
2003 $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
2004 $tax_query[] = array(
2005 'taxonomy' => 'post_tag',
2006 'terms' => $q['tag_slug__in'],
2011 if ( !empty($q['tag_slug__and']) ) {
2012 $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
2013 $tax_query[] = array(
2014 'taxonomy' => 'post_tag',
2015 'terms' => $q['tag_slug__and'],
2021 $this->tax_query = new WP_Tax_Query( $tax_query );
2024 * Fires after taxonomy-related query vars have been parsed.
2028 * @param WP_Query $this The WP_Query instance.
2030 do_action( 'parse_tax_query', $this );
2034 * Generate SQL for the WHERE clause based on passed search terms.
2038 * @global wpdb $wpdb
2039 * @param array $q Query variables.
2040 * @return string WHERE clause.
2042 protected function parse_search( &$q ) {
2047 // added slashes screw with quote grouping when done early, so done later
2048 $q['s'] = stripslashes( $q['s'] );
2049 if ( empty( $_GET['s'] ) && $this->is_main_query() )
2050 $q['s'] = urldecode( $q['s'] );
2051 // there are no line breaks in <input /> fields
2052 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
2053 $q['search_terms_count'] = 1;
2054 if ( ! empty( $q['sentence'] ) ) {
2055 $q['search_terms'] = array( $q['s'] );
2057 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
2058 $q['search_terms_count'] = count( $matches[0] );
2059 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
2060 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
2061 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
2062 $q['search_terms'] = array( $q['s'] );
2064 $q['search_terms'] = array( $q['s'] );
2068 $n = ! empty( $q['exact'] ) ? '' : '%';
2070 $q['search_orderby_title'] = array();
2071 foreach ( $q['search_terms'] as $term ) {
2073 $like = '%' . $wpdb->esc_like( $term ) . '%';
2074 $q['search_orderby_title'][] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like );
2077 $like = $n . $wpdb->esc_like( $term ) . $n;
2078 $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title LIKE %s) OR ($wpdb->posts.post_content LIKE %s))", $like, $like );
2079 $searchand = ' AND ';
2082 if ( ! empty( $search ) ) {
2083 $search = " AND ({$search}) ";
2084 if ( ! is_user_logged_in() )
2085 $search .= " AND ($wpdb->posts.post_password = '') ";
2092 * Check if the terms are suitable for searching.
2094 * Uses an array of stopwords (terms) that are excluded from the separate
2095 * term matching when searching for posts. The list of English stopwords is
2096 * the approximate search engines list, and is translatable.
2100 * @param array Terms to check.
2101 * @return array Terms that are not stopwords.
2103 protected function parse_search_terms( $terms ) {
2104 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
2107 $stopwords = $this->get_search_stopwords();
2109 foreach ( $terms as $term ) {
2110 // keep before/after spaces when term is for exact match
2111 if ( preg_match( '/^".+"$/', $term ) )
2112 $term = trim( $term, "\"'" );
2114 $term = trim( $term, "\"' " );
2116 // Avoid single A-Z.
2117 if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z]$/i', $term ) ) )
2120 if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
2130 * Retrieve stopwords used when parsing search terms.
2134 * @return array Stopwords.
2136 protected function get_search_stopwords() {
2137 if ( isset( $this->stopwords ) )
2138 return $this->stopwords;
2140 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
2141 * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
2142 * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
2144 $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',
2145 'Comma-separated list of search stopwords in your language' ) );
2147 $stopwords = array();
2148 foreach( $words as $word ) {
2149 $word = trim( $word, "\r\n\t " );
2151 $stopwords[] = $word;
2155 * Filter stopwords used when parsing search terms.
2159 * @param array $stopwords Stopwords.
2161 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
2162 return $this->stopwords;
2166 * Generate SQL for the ORDER BY condition based on passed search terms.
2168 * @global wpdb $wpdb
2169 * @param array $q Query variables.
2170 * @return string ORDER BY clause.
2172 protected function parse_search_order( &$q ) {
2175 if ( $q['search_terms_count'] > 1 ) {
2176 $num_terms = count( $q['search_orderby_title'] );
2177 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
2179 $search_orderby = '(CASE ';
2180 // sentence match in 'post_title'
2181 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_title LIKE %s THEN 1 ", $like );
2183 // sanity limit, sort as sentence when more than 6 terms
2184 // (few searches are longer than 6 terms and most titles are not)
2185 if ( $num_terms < 7 ) {
2186 // all words in title
2187 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
2188 // any word in title, not needed when $num_terms == 1
2189 if ( $num_terms > 1 )
2190 $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
2193 // sentence match in 'post_content'
2194 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 4 ", $like );
2195 $search_orderby .= 'ELSE 5 END)';
2197 // single word or sentence search
2198 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2201 return $search_orderby;
2205 * If the passed orderby value is allowed, convert the alias to a
2206 * properly-prefixed orderby value.
2211 * @global wpdb $wpdb WordPress database access abstraction object.
2213 * @param string $orderby Alias for the field to order by.
2214 * @return string|bool Table-prefixed value to used in the ORDER clause. False otherwise.
2216 protected function parse_orderby( $orderby ) {
2219 // Used to filter values.
2220 $allowed_keys = array(
2221 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2222 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2223 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2226 $meta_key = $this->get( 'meta_key' );
2227 if ( ! empty( $meta_key ) ) {
2228 $allowed_keys[] = $meta_key;
2229 $allowed_keys[] = 'meta_value';
2230 $allowed_keys[] = 'meta_value_num';
2233 if ( ! in_array( $orderby, $allowed_keys ) ) {
2237 switch ( $orderby ) {
2242 case 'post_modified':
2247 case 'comment_count':
2248 $orderby = "$wpdb->posts.{$orderby}";
2251 $orderby = 'RAND()';
2255 $type = $this->get( 'meta_type' );
2256 if ( ! empty( $type ) ) {
2257 $meta_type = $this->meta_query->get_cast_for_type( $type );
2258 $orderby = "CAST($wpdb->postmeta.meta_value AS {$meta_type})";
2260 $orderby = "$wpdb->postmeta.meta_value";
2263 case 'meta_value_num':
2264 $orderby = "$wpdb->postmeta.meta_value+0";
2267 $orderby = "$wpdb->posts.post_" . $orderby;
2275 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2280 * @param string $order The 'order' query variable.
2281 * @return string The sanitized 'order' query variable.
2283 protected function parse_order( $order ) {
2284 if ( ! is_string( $order ) || empty( $order ) ) {
2288 if ( 'ASC' === strtoupper( $order ) ) {
2296 * Sets the 404 property and saves whether query is feed.
2301 public function set_404() {
2302 $is_feed = $this->is_feed;
2304 $this->init_query_flags();
2305 $this->is_404 = true;
2307 $this->is_feed = $is_feed;
2311 * Retrieve query variable.
2316 * @param string $query_var Query variable key.
2317 * @param mixed $default Value to return if the query variable is not set. Default ''.
2320 public function get( $query_var, $default = '' ) {
2321 if ( isset( $this->query_vars[ $query_var ] ) ) {
2322 return $this->query_vars[ $query_var ];
2329 * Set query variable.
2334 * @param string $query_var Query variable key.
2335 * @param mixed $value Query variable value.
2337 public function set($query_var, $value) {
2338 $this->query_vars[$query_var] = $value;
2342 * Retrieve the posts based on query variables.
2344 * There are a few filters and actions that can be used to modify the post
2349 * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts.
2351 * @return array List of posts.
2353 public function get_posts() {
2356 $this->parse_query();
2359 * Fires after the query variable object is created, but before the actual query is run.
2361 * Note: If using conditional tags, use the method versions within the passed instance
2362 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2363 * like is_main_query() test against the global $wp_query instance, not the passed one.
2367 * @param WP_Query &$this The WP_Query instance (passed by reference).
2369 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2372 $q = &$this->query_vars;
2374 // Fill again in case pre_get_posts unset some vars.
2375 $q = $this->fill_query_vars($q);
2378 $this->meta_query = new WP_Meta_Query();
2379 $this->meta_query->parse_query_vars( $q );
2381 // Set a flag if a pre_get_posts hook changed the query vars.
2382 $hash = md5( serialize( $this->query_vars ) );
2383 if ( $hash != $this->query_vars_hash ) {
2384 $this->query_vars_changed = true;
2385 $this->query_vars_hash = $hash;
2389 // First let's clear some variables
2392 $whichmimetype = '';
2398 $post_status_join = false;
2401 if ( isset( $q['caller_get_posts'] ) ) {
2402 _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2403 if ( !isset( $q['ignore_sticky_posts'] ) )
2404 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2407 if ( !isset( $q['ignore_sticky_posts'] ) )
2408 $q['ignore_sticky_posts'] = false;
2410 if ( !isset($q['suppress_filters']) )
2411 $q['suppress_filters'] = false;
2413 if ( !isset($q['cache_results']) ) {
2414 if ( wp_using_ext_object_cache() )
2415 $q['cache_results'] = false;
2417 $q['cache_results'] = true;
2420 if ( !isset($q['update_post_term_cache']) )
2421 $q['update_post_term_cache'] = true;
2423 if ( !isset($q['update_post_meta_cache']) )
2424 $q['update_post_meta_cache'] = true;
2426 if ( !isset($q['post_type']) ) {
2427 if ( $this->is_search )
2428 $q['post_type'] = 'any';
2430 $q['post_type'] = '';
2432 $post_type = $q['post_type'];
2433 if ( empty( $q['posts_per_page'] ) ) {
2434 $q['posts_per_page'] = get_option( 'posts_per_page' );
2436 if ( isset($q['showposts']) && $q['showposts'] ) {
2437 $q['showposts'] = (int) $q['showposts'];
2438 $q['posts_per_page'] = $q['showposts'];
2440 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2441 $q['posts_per_page'] = $q['posts_per_archive_page'];
2442 if ( !isset($q['nopaging']) ) {
2443 if ( $q['posts_per_page'] == -1 ) {
2444 $q['nopaging'] = true;
2446 $q['nopaging'] = false;
2450 if ( $this->is_feed ) {
2451 // This overrides posts_per_page.
2452 if ( ! empty( $q['posts_per_rss'] ) ) {
2453 $q['posts_per_page'] = $q['posts_per_rss'];
2455 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2457 $q['nopaging'] = false;
2459 $q['posts_per_page'] = (int) $q['posts_per_page'];
2460 if ( $q['posts_per_page'] < -1 )
2461 $q['posts_per_page'] = abs($q['posts_per_page']);
2462 else if ( $q['posts_per_page'] == 0 )
2463 $q['posts_per_page'] = 1;
2465 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2466 $q['comments_per_page'] = get_option('comments_per_page');
2468 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2469 $this->is_page = true;
2470 $this->is_home = false;
2471 $q['page_id'] = get_option('page_on_front');
2474 if ( isset($q['page']) ) {
2475 $q['page'] = trim($q['page'], '/');
2476 $q['page'] = absint($q['page']);
2479 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2480 if ( isset($q['no_found_rows']) )
2481 $q['no_found_rows'] = (bool) $q['no_found_rows'];
2483 $q['no_found_rows'] = false;
2485 switch ( $q['fields'] ) {
2487 $fields = "$wpdb->posts.ID";
2490 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2493 $fields = "$wpdb->posts.*";
2496 if ( '' !== $q['menu_order'] )
2497 $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2499 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2501 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2502 if ( strlen($q['m']) > 5 )
2503 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2504 if ( strlen($q['m']) > 7 )
2505 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2506 if ( strlen($q['m']) > 9 )
2507 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2508 if ( strlen($q['m']) > 11 )
2509 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2510 if ( strlen($q['m']) > 13 )
2511 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2514 // Handle the other individual date parameters
2515 $date_parameters = array();
2517 if ( '' !== $q['hour'] )
2518 $date_parameters['hour'] = $q['hour'];
2520 if ( '' !== $q['minute'] )
2521 $date_parameters['minute'] = $q['minute'];
2523 if ( '' !== $q['second'] )
2524 $date_parameters['second'] = $q['second'];
2527 $date_parameters['year'] = $q['year'];
2529 if ( $q['monthnum'] )
2530 $date_parameters['monthnum'] = $q['monthnum'];
2533 $date_parameters['week'] = $q['w'];
2536 $date_parameters['day'] = $q['day'];
2538 if ( $date_parameters ) {
2539 $date_query = new WP_Date_Query( array( $date_parameters ) );
2540 $where .= $date_query->get_sql();
2542 unset( $date_parameters, $date_query );
2544 // Handle complex date queries
2545 if ( ! empty( $q['date_query'] ) ) {
2546 $this->date_query = new WP_Date_Query( $q['date_query'] );
2547 $where .= $this->date_query->get_sql();
2551 // If we've got a post_type AND it's not "any" post_type.
2552 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2553 foreach ( (array)$q['post_type'] as $_post_type ) {
2554 $ptype_obj = get_post_type_object($_post_type);
2555 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2558 if ( ! $ptype_obj->hierarchical ) {
2559 // Non-hierarchical post types can directly use 'name'.
2560 $q['name'] = $q[ $ptype_obj->query_var ];
2562 // Hierarchical post types will operate through 'pagename'.
2563 $q['pagename'] = $q[ $ptype_obj->query_var ];
2567 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2573 if ( '' != $q['name'] ) {
2574 $q['name'] = sanitize_title_for_query( $q['name'] );
2575 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2576 } elseif ( '' != $q['pagename'] ) {
2577 if ( isset($this->queried_object_id) ) {
2578 $reqpage = $this->queried_object_id;
2580 if ( 'page' != $q['post_type'] ) {
2581 foreach ( (array)$q['post_type'] as $_post_type ) {
2582 $ptype_obj = get_post_type_object($_post_type);
2583 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2586 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2592 $reqpage = get_page_by_path($q['pagename']);
2594 if ( !empty($reqpage) )
2595 $reqpage = $reqpage->ID;
2600 $page_for_posts = get_option('page_for_posts');
2601 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2602 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2603 $q['name'] = $q['pagename'];
2604 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2605 $reqpage_obj = get_post( $reqpage );
2606 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2607 $this->is_attachment = true;
2608 $post_type = $q['post_type'] = 'attachment';
2609 $this->is_page = true;
2610 $q['attachment_id'] = $reqpage;
2613 } elseif ( '' != $q['attachment'] ) {
2614 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2615 $q['name'] = $q['attachment'];
2616 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2620 if ( intval($q['comments_popup']) )
2621 $q['p'] = absint($q['comments_popup']);
2623 // If an attachment is requested by number, let it supersede any post number.
2624 if ( $q['attachment_id'] )
2625 $q['p'] = absint($q['attachment_id']);
2627 // If a post number is specified, load that post
2629 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2630 } elseif ( $q['post__in'] ) {
2631 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2632 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2633 } elseif ( $q['post__not_in'] ) {
2634 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
2635 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2638 if ( is_numeric( $q['post_parent'] ) ) {
2639 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2640 } elseif ( $q['post_parent__in'] ) {
2641 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2642 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2643 } elseif ( $q['post_parent__not_in'] ) {
2644 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
2645 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2648 if ( $q['page_id'] ) {
2649 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2650 $q['p'] = $q['page_id'];
2651 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2655 // If a search pattern is specified, load the posts that match.
2656 if ( ! empty( $q['s'] ) ) {
2657 $search = $this->parse_search( $q );
2661 * Filter the search SQL that is used in the WHERE clause of WP_Query.
2665 * @param string $search Search SQL for WHERE clause.
2666 * @param WP_Query $this The current WP_Query object.
2668 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2671 if ( !$this->is_singular ) {
2672 $this->parse_tax_query( $q );
2674 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2676 $join .= $clauses['join'];
2677 $where .= $clauses['where'];
2680 if ( $this->is_tax ) {
2681 if ( empty($post_type) ) {
2682 // Do a fully inclusive search for currently registered post types of queried taxonomies
2683 $post_type = array();
2684 $taxonomies = wp_list_pluck( $this->tax_query->queries, 'taxonomy' );
2685 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2686 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2687 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2692 elseif ( count( $post_type ) == 1 )
2693 $post_type = $post_type[0];
2695 $post_status_join = true;
2696 } elseif ( in_array('attachment', (array) $post_type) ) {
2697 $post_status_join = true;
2702 if ( !empty($this->tax_query->queries) ) {
2703 $tax_query_in_and = wp_list_filter( $this->tax_query->queries, array( 'operator' => 'NOT IN' ), 'NOT' );
2704 if ( !empty( $tax_query_in_and ) ) {
2705 if ( !isset( $q['taxonomy'] ) ) {
2706 foreach ( $tax_query_in_and as $a_tax_query ) {
2707 if ( !in_array( $a_tax_query['taxonomy'], array( 'category', 'post_tag' ) ) ) {
2708 $q['taxonomy'] = $a_tax_query['taxonomy'];
2709 if ( 'slug' == $a_tax_query['field'] )
2710 $q['term'] = $a_tax_query['terms'][0];
2712 $q['term_id'] = $a_tax_query['terms'][0];
2719 $cat_query = wp_list_filter( $tax_query_in_and, array( 'taxonomy' => 'category' ) );
2720 if ( ! empty( $cat_query ) ) {
2721 $cat_query = reset( $cat_query );
2723 if ( ! empty( $cat_query['terms'][0] ) ) {
2724 $the_cat = get_term_by( $cat_query['field'], $cat_query['terms'][0], 'category' );
2726 $this->set( 'cat', $the_cat->term_id );
2727 $this->set( 'category_name', $the_cat->slug );
2732 unset( $cat_query );
2734 $tag_query = wp_list_filter( $tax_query_in_and, array( 'taxonomy' => 'post_tag' ) );
2735 if ( ! empty( $tag_query ) ) {
2736 $tag_query = reset( $tag_query );
2738 if ( ! empty( $tag_query['terms'][0] ) ) {
2739 $the_tag = get_term_by( $tag_query['field'], $tag_query['terms'][0], 'post_tag' );
2741 $this->set( 'tag_id', $the_tag->term_id );
2745 unset( $tag_query );
2749 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2750 $groupby = "{$wpdb->posts}.ID";
2753 // Author/user stuff
2755 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2756 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2757 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2758 foreach ( $authors as $author ) {
2759 $key = $author > 0 ? 'author__in' : 'author__not_in';
2760 $q[$key][] = abs( $author );
2762 $q['author'] = implode( ',', $authors );
2765 if ( ! empty( $q['author__not_in'] ) ) {
2766 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2767 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2768 } elseif ( ! empty( $q['author__in'] ) ) {
2769 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2770 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2773 // Author stuff for nice URLs
2775 if ( '' != $q['author_name'] ) {
2776 if ( strpos($q['author_name'], '/') !== false ) {
2777 $q['author_name'] = explode('/', $q['author_name']);
2778 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2779 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2781 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2784 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2785 $q['author'] = get_user_by('slug', $q['author_name']);
2787 $q['author'] = $q['author']->ID;
2788 $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2791 // MIME-Type stuff for attachment browsing
2793 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2794 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2796 $where .= $search . $whichauthor . $whichmimetype;
2798 if ( ! isset( $q['order'] ) ) {
2799 $q['order'] = 'DESC';
2801 $q['order'] = $this->parse_order( $q['order'] );
2805 if ( empty( $q['orderby'] ) ) {
2807 * Boolean false or empty array blanks out ORDER BY,
2808 * while leaving the value unset or otherwise empty sets the default.
2810 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2813 $orderby = "$wpdb->posts.post_date " . $q['order'];
2815 } elseif ( 'none' == $q['orderby'] ) {
2817 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2818 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2819 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2820 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2822 $orderby_array = array();
2823 if ( is_array( $q['orderby'] ) ) {
2824 foreach ( $q['orderby'] as $_orderby => $order ) {
2825 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2826 $parsed = $this->parse_orderby( $orderby );
2832 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2834 $orderby = implode( ', ', $orderby_array );
2837 $q['orderby'] = urldecode( $q['orderby'] );
2838 $q['orderby'] = addslashes_gpc( $q['orderby'] );
2840 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
2841 $parsed = $this->parse_orderby( $orderby );
2842 // Only allow certain values for safety.
2847 $orderby_array[] = $parsed;
2849 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
2851 if ( empty( $orderby ) ) {
2852 $orderby = "$wpdb->posts.post_date ".$q['order'];
2854 $orderby .= " {$q['order']}";
2859 // Order search results by relevance only when another "orderby" is not specified in the query.
2860 if ( ! empty( $q['s'] ) ) {
2861 $search_orderby = '';
2862 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
2863 $search_orderby = $this->parse_search_order( $q );
2866 * Filter the ORDER BY used when ordering search results.
2870 * @param string $search_orderby The ORDER BY clause.
2871 * @param WP_Query $this The current WP_Query instance.
2873 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
2874 if ( $search_orderby )
2875 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
2878 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
2879 $post_type_cap = 'multiple_post_type';
2881 if ( is_array( $post_type ) )
2882 $post_type = reset( $post_type );
2883 $post_type_object = get_post_type_object( $post_type );
2884 if ( empty( $post_type_object ) )
2885 $post_type_cap = $post_type;
2888 if ( isset( $q['post_password'] ) ) {
2889 $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
2890 if ( empty( $q['perm'] ) ) {
2891 $q['perm'] = 'readable';
2893 } elseif ( isset( $q['has_password'] ) ) {
2894 $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
2897 if ( 'any' == $post_type ) {
2898 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
2899 if ( empty( $in_search_post_types ) )
2900 $where .= ' AND 1=0 ';
2902 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')";
2903 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
2904 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
2905 } elseif ( ! empty( $post_type ) ) {
2906 $where .= " AND $wpdb->posts.post_type = '$post_type'";
2907 $post_type_object = get_post_type_object ( $post_type );
2908 } elseif ( $this->is_attachment ) {
2909 $where .= " AND $wpdb->posts.post_type = 'attachment'";
2910 $post_type_object = get_post_type_object ( 'attachment' );
2911 } elseif ( $this->is_page ) {
2912 $where .= " AND $wpdb->posts.post_type = 'page'";
2913 $post_type_object = get_post_type_object ( 'page' );
2915 $where .= " AND $wpdb->posts.post_type = 'post'";
2916 $post_type_object = get_post_type_object ( 'post' );
2919 $edit_cap = 'edit_post';
2920 $read_cap = 'read_post';
2922 if ( ! empty( $post_type_object ) ) {
2923 $edit_others_cap = $post_type_object->cap->edit_others_posts;
2924 $read_private_cap = $post_type_object->cap->read_private_posts;
2926 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
2927 $read_private_cap = 'read_private_' . $post_type_cap . 's';
2930 $user_id = get_current_user_id();
2932 if ( ! empty( $q['post_status'] ) ) {
2933 $statuswheres = array();
2934 $q_status = $q['post_status'];
2935 if ( ! is_array( $q_status ) )
2936 $q_status = explode(',', $q_status);
2937 $r_status = array();
2938 $p_status = array();
2939 $e_status = array();
2940 if ( in_array( 'any', $q_status ) ) {
2941 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
2942 if ( ! in_array( $status, $q_status ) ) {
2943 $e_status[] = "$wpdb->posts.post_status <> '$status'";
2947 foreach ( get_post_stati() as $status ) {
2948 if ( in_array( $status, $q_status ) ) {
2949 if ( 'private' == $status )
2950 $p_status[] = "$wpdb->posts.post_status = '$status'";
2952 $r_status[] = "$wpdb->posts.post_status = '$status'";
2957 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
2958 $r_status = array_merge($r_status, $p_status);
2962 if ( !empty($e_status) ) {
2963 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
2965 if ( !empty($r_status) ) {
2966 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
2967 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
2969 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
2971 if ( !empty($p_status) ) {
2972 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
2973 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
2975 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
2977 if ( $post_status_join ) {
2978 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
2979 foreach ( $statuswheres as $index => $statuswhere )
2980 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
2982 $where_status = implode( ' OR ', $statuswheres );
2983 if ( ! empty( $where_status ) ) {
2984 $where .= " AND ($where_status)";
2986 } elseif ( !$this->is_singular ) {
2987 $where .= " AND ($wpdb->posts.post_status = 'publish'";
2989 // Add public states.
2990 $public_states = get_post_stati( array('public' => true) );
2991 foreach ( (array) $public_states as $state ) {
2992 if ( 'publish' == $state ) // Publish is hard-coded above.
2994 $where .= " OR $wpdb->posts.post_status = '$state'";
2997 if ( $this->is_admin ) {
2998 // Add protected states that should show in the admin all list.
2999 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3000 foreach ( (array) $admin_all_states as $state )
3001 $where .= " OR $wpdb->posts.post_status = '$state'";
3004 if ( is_user_logged_in() ) {
3005 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3006 $private_states = get_post_stati( array('private' => true) );
3007 foreach ( (array) $private_states as $state )
3008 $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'";
3014 if ( !empty( $this->meta_query->queries ) ) {
3015 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
3016 $join .= $clauses['join'];
3017 $where .= $clauses['where'];
3021 * Apply filters on where and join prior to paging so that any
3022 * manipulations to them are reflected in the paging by day queries.
3024 if ( !$q['suppress_filters'] ) {
3026 * Filter the WHERE clause of the query.
3030 * @param string $where The WHERE clause of the query.
3031 * @param WP_Query &$this The WP_Query instance (passed by reference).
3033 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3036 * Filter the JOIN clause of the query.
3040 * @param string $where The JOIN clause of the query.
3041 * @param WP_Query &$this The WP_Query instance (passed by reference).
3043 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3047 if ( empty($q['nopaging']) && !$this->is_singular ) {
3048 $page = absint($q['paged']);
3052 if ( empty($q['offset']) ) {
3053 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3054 } else { // we're ignoring $page and using 'offset'
3055 $q['offset'] = absint($q['offset']);
3056 $pgstrt = $q['offset'] . ', ';
3058 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3062 if ( $this->is_comment_feed && ! $this->is_singular ) {
3063 if ( $this->is_archive || $this->is_search ) {
3064 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3065 $cwhere = "WHERE comment_approved = '1' $where";
3066 $cgroupby = "$wpdb->comments.comment_id";
3067 } else { // Other non singular e.g. front
3068 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3069 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
3073 if ( !$q['suppress_filters'] ) {
3075 * Filter the JOIN clause of the comments feed query before sending.
3079 * @param string $cjoin The JOIN clause of the query.
3080 * @param WP_Query &$this The WP_Query instance (passed by reference).
3082 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3085 * Filter the WHERE clause of the comments feed query before sending.
3089 * @param string $cwhere The WHERE clause of the query.
3090 * @param WP_Query &$this The WP_Query instance (passed by reference).
3092 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3095 * Filter the GROUP BY clause of the comments feed query before sending.
3099 * @param string $cgroupby The GROUP BY clause of the query.
3100 * @param WP_Query &$this The WP_Query instance (passed by reference).
3102 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3105 * Filter the ORDER BY clause of the comments feed query before sending.
3109 * @param string $corderby The ORDER BY clause of the query.
3110 * @param WP_Query &$this The WP_Query instance (passed by reference).
3112 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3115 * Filter the LIMIT clause of the comments feed query before sending.
3119 * @param string $climits The JOIN clause of the query.
3120 * @param WP_Query &$this The WP_Query instance (passed by reference).
3122 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3124 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3125 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3127 $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3128 $this->comment_count = count($this->comments);
3130 $post_ids = array();
3132 foreach ( $this->comments as $comment )
3133 $post_ids[] = (int) $comment->comment_post_ID;
3135 $post_ids = join(',', $post_ids);
3138 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3143 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3146 * Apply post-paging filters on where and join. Only plugins that
3147 * manipulate paging queries should use these hooks.
3149 if ( !$q['suppress_filters'] ) {
3151 * Filter the WHERE clause of the query.
3153 * Specifically for manipulating paging queries.
3157 * @param string $where The WHERE clause of the query.
3158 * @param WP_Query &$this The WP_Query instance (passed by reference).
3160 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3163 * Filter the GROUP BY clause of the query.
3167 * @param string $groupby The GROUP BY clause of the query.
3168 * @param WP_Query &$this The WP_Query instance (passed by reference).
3170 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3173 * Filter the JOIN clause of the query.
3175 * Specifically for manipulating paging queries.
3179 * @param string $join The JOIN clause of the query.
3180 * @param WP_Query &$this The WP_Query instance (passed by reference).
3182 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3185 * Filter the ORDER BY clause of the query.
3189 * @param string $orderby The ORDER BY clause of the query.
3190 * @param WP_Query &$this The WP_Query instance (passed by reference).
3192 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3195 * Filter the DISTINCT clause of the query.
3199 * @param string $distinct The DISTINCT clause of the query.
3200 * @param WP_Query &$this The WP_Query instance (passed by reference).
3202 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3205 * Filter the LIMIT clause of the query.
3209 * @param string $limits The LIMIT clause of the query.
3210 * @param WP_Query &$this The WP_Query instance (passed by reference).
3212 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3215 * Filter the SELECT clause of the query.
3219 * @param string $fields The SELECT clause of the query.
3220 * @param WP_Query &$this The WP_Query instance (passed by reference).
3222 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3225 * Filter all query clauses at once, for convenience.
3227 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3228 * fields (SELECT), and LIMITS clauses.
3232 * @param array $clauses The list of clauses for the query.
3233 * @param WP_Query &$this The WP_Query instance (passed by reference).
3235 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3237 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3238 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3239 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3240 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3241 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3242 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3243 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3247 * Fires to announce the query's current selection parameters.
3249 * For use by caching plugins.
3253 * @param string $selection The assembled selection query.
3255 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3258 * Filter again for the benefit of caching plugins.
3259 * Regular plugins should use the hooks above.
3261 if ( !$q['suppress_filters'] ) {
3263 * Filter the WHERE clause of the query.
3265 * For use by caching plugins.
3269 * @param string $where The WHERE clause of the query.
3270 * @param WP_Query &$this The WP_Query instance (passed by reference).
3272 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3275 * Filter the GROUP BY clause of the query.
3277 * For use by caching plugins.
3281 * @param string $groupby The GROUP BY clause of the query.
3282 * @param WP_Query &$this The WP_Query instance (passed by reference).
3284 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3287 * Filter the JOIN clause of the query.
3289 * For use by caching plugins.
3293 * @param string $join The JOIN clause of the query.
3294 * @param WP_Query &$this The WP_Query instance (passed by reference).
3296 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3299 * Filter the ORDER BY clause of the query.
3301 * For use by caching plugins.
3305 * @param string $orderby The ORDER BY clause of the query.
3306 * @param WP_Query &$this The WP_Query instance (passed by reference).
3308 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3311 * Filter the DISTINCT clause of the query.
3313 * For use by caching plugins.
3317 * @param string $distinct The DISTINCT clause of the query.
3318 * @param WP_Query &$this The WP_Query instance (passed by reference).
3320 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3323 * Filter the SELECT clause of the query.
3325 * For use by caching plugins.
3329 * @param string $fields The SELECT clause of the query.
3330 * @param WP_Query &$this The WP_Query instance (passed by reference).
3332 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3335 * Filter the LIMIT clause of the query.
3337 * For use by caching plugins.
3341 * @param string $limits The LIMIT clause of the query.
3342 * @param WP_Query &$this The WP_Query instance (passed by reference).
3344 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3347 * Filter all query clauses at once, for convenience.
3349 * For use by caching plugins.
3351 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3352 * fields (SELECT), and LIMITS clauses.
3356 * @param array $pieces The pieces of the query.
3357 * @param WP_Query &$this The WP_Query instance (passed by reference).
3359 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3361 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3362 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3363 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3364 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3365 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3366 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3367 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3370 if ( ! empty($groupby) )
3371 $groupby = 'GROUP BY ' . $groupby;
3372 if ( !empty( $orderby ) )
3373 $orderby = 'ORDER BY ' . $orderby;
3376 if ( !$q['no_found_rows'] && !empty($limits) )
3377 $found_rows = 'SQL_CALC_FOUND_ROWS';
3379 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3381 if ( !$q['suppress_filters'] ) {
3383 * Filter the completed SQL query before sending.
3387 * @param array $request The complete SQL query.
3388 * @param WP_Query &$this The WP_Query instance (passed by reference).
3390 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3393 if ( 'ids' == $q['fields'] ) {
3394 $this->posts = $wpdb->get_col( $this->request );
3395 $this->post_count = count( $this->posts );
3396 $this->set_found_posts( $q, $limits );
3398 return array_map( 'intval', $this->posts );
3401 if ( 'id=>parent' == $q['fields'] ) {
3402 $this->posts = $wpdb->get_results( $this->request );
3403 $this->post_count = count( $this->posts );
3404 $this->set_found_posts( $q, $limits );
3407 foreach ( $this->posts as $post ) {
3408 $r[ (int) $post->ID ] = (int) $post->post_parent;
3413 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3416 * Filter whether to split the query.
3418 * Splitting the query will cause it to fetch just the IDs of the found posts
3419 * (and then individually fetch each post by ID), rather than fetching every
3420 * complete row at once. One massive result vs. many small results.
3424 * @param bool $split_the_query Whether or not to split the query.
3425 * @param WP_Query $this The WP_Query instance.
3427 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3429 if ( $split_the_query ) {
3430 // First get the IDs and then fill in the objects
3432 $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3435 * Filter the Post IDs SQL request before sending.
3439 * @param string $request The post ID request.
3440 * @param WP_Query $this The WP_Query instance.
3442 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3444 $ids = $wpdb->get_col( $this->request );
3447 $this->posts = $ids;
3448 $this->set_found_posts( $q, $limits );
3449 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3451 $this->posts = array();
3454 $this->posts = $wpdb->get_results( $this->request );
3455 $this->set_found_posts( $q, $limits );
3458 // Convert to WP_Post objects
3460 $this->posts = array_map( 'get_post', $this->posts );
3462 if ( ! $q['suppress_filters'] ) {
3464 * Filter the raw post results array, prior to status checks.
3468 * @param array $posts The post results array.
3469 * @param WP_Query &$this The WP_Query instance (passed by reference).
3471 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3474 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3475 /** This filter is documented in wp-includes/query.php */
3476 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3478 /** This filter is documented in wp-includes/query.php */
3479 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3481 /** This filter is documented in wp-includes/query.php */
3482 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3483 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3485 /** This filter is documented in wp-includes/query.php */
3486 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3487 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3489 /** This filter is documented in wp-includes/query.php */
3490 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3492 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3493 $this->comments = $wpdb->get_results($comments_request);
3494 $this->comment_count = count($this->comments);
3497 // Check post status to determine if post should be displayed.
3498 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3499 $status = get_post_status($this->posts[0]);
3500 $post_status_obj = get_post_status_object($status);
3501 //$type = get_post_type($this->posts[0]);
3502 if ( !$post_status_obj->public ) {
3503 if ( ! is_user_logged_in() ) {
3504 // User must be logged in to view unpublished posts.
3505 $this->posts = array();
3507 if ( $post_status_obj->protected ) {
3508 // User must have edit permissions on the draft to preview.
3509 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3510 $this->posts = array();
3512 $this->is_preview = true;
3513 if ( 'future' != $status )
3514 $this->posts[0]->post_date = current_time('mysql');
3516 } elseif ( $post_status_obj->private ) {
3517 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3518 $this->posts = array();
3520 $this->posts = array();
3525 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3527 * Filter the single post for preview mode.
3531 * @param WP_Post $post_preview The Post object.
3532 * @param WP_Query &$this The WP_Query instance (passed by reference).
3534 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3538 // Put sticky posts at the top of the posts array
3539 $sticky_posts = get_option('sticky_posts');
3540 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3541 $num_posts = count($this->posts);
3543 // Loop over posts and relocate stickies to the front.
3544 for ( $i = 0; $i < $num_posts; $i++ ) {
3545 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3546 $sticky_post = $this->posts[$i];
3547 // Remove sticky from current position
3548 array_splice($this->posts, $i, 1);
3549 // Move to front, after other stickies
3550 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3551 // Increment the sticky offset. The next sticky will be placed at this offset.
3553 // Remove post from sticky posts array
3554 $offset = array_search($sticky_post->ID, $sticky_posts);
3555 unset( $sticky_posts[$offset] );
3559 // If any posts have been excluded specifically, Ignore those that are sticky.
3560 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3561 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3563 // Fetch sticky posts that weren't in the query results
3564 if ( !empty($sticky_posts) ) {
3565 $stickies = get_posts( array(
3566 'post__in' => $sticky_posts,
3567 'post_type' => $post_type,
3568 'post_status' => 'publish',
3572 foreach ( $stickies as $sticky_post ) {
3573 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3579 if ( ! $q['suppress_filters'] ) {
3581 * Filter the array of retrieved posts after they've been fetched and
3582 * internally processed.
3586 * @param array $posts The array of retrieved posts.
3587 * @param WP_Query &$this The WP_Query instance (passed by reference).
3589 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3592 // Ensure that any posts added/modified via one of the filters above are
3593 // of the type WP_Post and are filtered.
3594 if ( $this->posts ) {
3595 $this->post_count = count( $this->posts );
3597 $this->posts = array_map( 'get_post', $this->posts );
3599 if ( $q['cache_results'] )
3600 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3602 $this->post = reset( $this->posts );
3604 $this->post_count = 0;
3605 $this->posts = array();
3608 return $this->posts;
3612 * Set up the amount of found posts and the number of pages (if limit clause was used)
3613 * for the current query.
3618 private function set_found_posts( $q, $limits ) {
3621 // Bail if posts is an empty array. Continue if posts is an empty string,
3622 // null, or false to accommodate caching plugins that fill posts later.
3623 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3626 if ( ! empty( $limits ) ) {
3628 * Filter the query to run for retrieving the found posts.
3632 * @param string $found_posts The query to run to find the found posts.
3633 * @param WP_Query &$this The WP_Query instance (passed by reference).
3635 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3637 $this->found_posts = count( $this->posts );
3641 * Filter the number of found posts for the query.
3645 * @param int $found_posts The number of posts found.
3646 * @param WP_Query &$this The WP_Query instance (passed by reference).
3648 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3650 if ( ! empty( $limits ) )
3651 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3655 * Set up the next post and iterate current post index.
3660 * @return WP_Post Next post.
3662 public function next_post() {
3664 $this->current_post++;
3666 $this->post = $this->posts[$this->current_post];
3671 * Sets up the current post.
3673 * Retrieves the next post, sets up the post, sets the 'in the loop'
3679 * @uses do_action_ref_array() Calls 'loop_start' if loop has just started
3681 public function the_post() {
3683 $this->in_the_loop = true;
3685 if ( $this->current_post == -1 ) // loop has just started
3687 * Fires once the loop is started.
3691 * @param WP_Query &$this The WP_Query instance (passed by reference).
3693 do_action_ref_array( 'loop_start', array( &$this ) );
3695 $post = $this->next_post();
3696 setup_postdata($post);
3700 * Whether there are more posts available in the loop.
3702 * Calls action 'loop_end', when the loop is complete.
3706 * @uses do_action_ref_array() Calls 'loop_end' if loop is ended
3708 * @return bool True if posts are available, false if end of loop.
3710 public function have_posts() {
3711 if ( $this->current_post + 1 < $this->post_count ) {
3713 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3715 * Fires once the loop has ended.
3719 * @param WP_Query &$this The WP_Query instance (passed by reference).
3721 do_action_ref_array( 'loop_end', array( &$this ) );
3722 // Do some cleaning up after the loop
3723 $this->rewind_posts();
3726 $this->in_the_loop = false;
3731 * Rewind the posts and reset post index.
3736 public function rewind_posts() {
3737 $this->current_post = -1;
3738 if ( $this->post_count > 0 ) {
3739 $this->post = $this->posts[0];
3744 * Iterate current comment index and return comment object.
3749 * @return object Comment object.
3751 public function next_comment() {
3752 $this->current_comment++;
3754 $this->comment = $this->comments[$this->current_comment];
3755 return $this->comment;
3759 * Sets up the current comment.
3763 * @global object $comment Current comment.
3764 * @uses do_action() Calls 'comment_loop_start' hook when first comment is processed.
3766 public function the_comment() {
3769 $comment = $this->next_comment();
3771 if ( $this->current_comment == 0 ) {
3773 * Fires once the comment loop is started.
3777 do_action( 'comment_loop_start' );
3782 * Whether there are more comments available.
3784 * Automatically rewinds comments when finished.
3789 * @return bool True, if more comments. False, if no more posts.
3791 public function have_comments() {
3792 if ( $this->current_comment + 1 < $this->comment_count ) {
3794 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
3795 $this->rewind_comments();
3802 * Rewind the comments, resets the comment index and comment to first.
3807 public function rewind_comments() {
3808 $this->current_comment = -1;
3809 if ( $this->comment_count > 0 ) {
3810 $this->comment = $this->comments[0];
3815 * Sets up the WordPress query by parsing query string.
3820 * @param string $query URL query string.
3821 * @return array List of posts.
3823 public function query( $query ) {
3825 $this->query = $this->query_vars = wp_parse_args( $query );
3826 return $this->get_posts();
3830 * Retrieve queried object.
3832 * If queried object is not set, then the queried object will be set from
3833 * the category, tag, taxonomy, posts page, single post, page, or author
3834 * query variable. After it is set up, it will be returned.
3841 public function get_queried_object() {
3842 if ( isset($this->queried_object) )
3843 return $this->queried_object;
3845 $this->queried_object = null;
3846 $this->queried_object_id = 0;
3848 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
3849 if ( $this->is_category ) {
3850 if ( $this->get( 'cat' ) ) {
3851 $term = get_term( $this->get( 'cat' ), 'category' );
3852 } elseif ( $this->get( 'category_name' ) ) {
3853 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
3855 } elseif ( $this->is_tag ) {
3856 if ( $this->get( 'tag_id' ) ) {
3857 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
3858 } elseif ( $this->get( 'tag' ) ) {
3859 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
3862 $tax_query_in_and = wp_list_filter( $this->tax_query->queries, array( 'operator' => 'NOT IN' ), 'NOT' );
3863 $query = reset( $tax_query_in_and );
3865 if ( $query['terms'] ) {
3866 if ( 'term_id' == $query['field'] ) {
3867 $term = get_term( reset( $query['terms'] ), $query['taxonomy'] );
3869 $term = get_term_by( $query['field'], reset( $query['terms'] ), $query['taxonomy'] );
3874 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
3875 $this->queried_object = $term;
3876 $this->queried_object_id = (int) $term->term_id;
3878 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
3879 _make_cat_compat( $this->queried_object );
3881 } elseif ( $this->is_post_type_archive ) {
3882 $post_type = $this->get( 'post_type' );
3883 if ( is_array( $post_type ) )
3884 $post_type = reset( $post_type );
3885 $this->queried_object = get_post_type_object( $post_type );
3886 } elseif ( $this->is_posts_page ) {
3887 $page_for_posts = get_option('page_for_posts');
3888 $this->queried_object = get_post( $page_for_posts );
3889 $this->queried_object_id = (int) $this->queried_object->ID;
3890 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
3891 $this->queried_object = $this->post;
3892 $this->queried_object_id = (int) $this->post->ID;
3893 } elseif ( $this->is_author ) {
3894 $this->queried_object_id = (int) $this->get('author');
3895 $this->queried_object = get_userdata( $this->queried_object_id );
3898 return $this->queried_object;
3902 * Retrieve ID of the current queried object.
3909 public function get_queried_object_id() {
3910 $this->get_queried_object();
3912 if ( isset($this->queried_object_id) ) {
3913 return $this->queried_object_id;
3922 * Sets up the WordPress query, if parameter is not empty.
3927 * @param string $query URL query string.
3930 public function __construct($query = '') {
3931 if ( ! empty($query) ) {
3932 $this->query($query);
3937 * Make private properties readable for backwards compatibility.
3942 * @param string $name Property to get.
3943 * @return mixed Property.
3945 public function __get( $name ) {
3946 return $this->$name;
3950 * Make private properties settable for backwards compatibility.
3955 * @param string $name Property to check if set.
3956 * @return bool Whether the property is set.
3958 public function __isset( $name ) {
3959 return isset( $this->$name );
3963 * Make private properties settable for backwards compatibility.
3968 * @param string $name Property to unset.
3970 public function __unset( $name ) {
3971 unset( $this->$name );
3975 * Make private/protected methods readable for backwards compatibility.
3980 * @param callable $name Method to call.
3981 * @param array $arguments Arguments to pass when calling.
3982 * @return mixed|bool Return value of the callback, otherwise false.
3984 public function __call( $name, $arguments ) {
3985 return call_user_func_array( array( $this, $name ), $arguments );
3989 * Is the query for an existing archive page?
3991 * Month, Year, Category, Author, Post Type archive...
3997 public function is_archive() {
3998 return (bool) $this->is_archive;
4002 * Is the query for an existing post type archive page?
4006 * @param mixed $post_types Optional. Post type or array of posts types to check against.
4009 public function is_post_type_archive( $post_types = '' ) {
4010 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4011 return (bool) $this->is_post_type_archive;
4013 $post_type = $this->get( 'post_type' );
4014 if ( is_array( $post_type ) )
4015 $post_type = reset( $post_type );
4016 $post_type_object = get_post_type_object( $post_type );
4018 return in_array( $post_type_object->name, (array) $post_types );
4022 * Is the query for an existing attachment page?
4026 * @param mixed $attachment Attachment ID, title, slug, or array of such.
4029 public function is_attachment( $attachment = '' ) {
4030 if ( ! $this->is_attachment ) {
4034 if ( empty( $attachment ) ) {
4038 $attachment = (array) $attachment;
4040 $post_obj = $this->get_queried_object();
4042 if ( in_array( $post_obj->ID, $attachment ) ) {
4044 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4046 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4053 * Is the query for an existing author archive page?
4055 * If the $author parameter is specified, this function will additionally
4056 * check if the query is for one of the authors specified.
4060 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4063 public function is_author( $author = '' ) {
4064 if ( !$this->is_author )
4067 if ( empty($author) )
4070 $author_obj = $this->get_queried_object();
4072 $author = (array) $author;
4074 if ( in_array( $author_obj->ID, $author ) )
4076 elseif ( in_array( $author_obj->nickname, $author ) )
4078 elseif ( in_array( $author_obj->user_nicename, $author ) )
4085 * Is the query for an existing category archive page?
4087 * If the $category parameter is specified, this function will additionally
4088 * check if the query is for one of the categories specified.
4092 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4095 public function is_category( $category = '' ) {
4096 if ( !$this->is_category )
4099 if ( empty($category) )
4102 $cat_obj = $this->get_queried_object();
4104 $category = (array) $category;
4106 if ( in_array( $cat_obj->term_id, $category ) )
4108 elseif ( in_array( $cat_obj->name, $category ) )
4110 elseif ( in_array( $cat_obj->slug, $category ) )
4117 * Is the query for an existing tag archive page?
4119 * If the $tag parameter is specified, this function will additionally
4120 * check if the query is for one of the tags specified.
4124 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4127 public function is_tag( $tag = '' ) {
4128 if ( ! $this->is_tag )
4131 if ( empty( $tag ) )
4134 $tag_obj = $this->get_queried_object();
4136 $tag = (array) $tag;
4138 if ( in_array( $tag_obj->term_id, $tag ) )
4140 elseif ( in_array( $tag_obj->name, $tag ) )
4142 elseif ( in_array( $tag_obj->slug, $tag ) )
4149 * Is the query for an existing taxonomy archive page?
4151 * If the $taxonomy parameter is specified, this function will additionally
4152 * check if the query is for that specific $taxonomy.
4154 * If the $term parameter is specified in addition to the $taxonomy parameter,
4155 * this function will additionally check if the query is for one of the terms
4160 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4161 * @param mixed $term. Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4164 public function is_tax( $taxonomy = '', $term = '' ) {
4165 global $wp_taxonomies;
4167 if ( !$this->is_tax )
4170 if ( empty( $taxonomy ) )
4173 $queried_object = $this->get_queried_object();
4174 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4175 $term_array = (array) $term;
4177 // Check that the taxonomy matches.
4178 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4181 // Only a Taxonomy provided.
4182 if ( empty( $term ) )
4185 return isset( $queried_object->term_id ) &&
4186 count( array_intersect(
4187 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4193 * Whether the current URL is within the comments popup window.
4199 public function is_comments_popup() {
4200 return (bool) $this->is_comments_popup;
4204 * Is the query for an existing date archive?
4210 public function is_date() {
4211 return (bool) $this->is_date;
4215 * Is the query for an existing day archive?
4221 public function is_day() {
4222 return (bool) $this->is_day;
4226 * Is the query for a feed?
4230 * @param string|array $feeds Optional feed types to check.
4233 public function is_feed( $feeds = '' ) {
4234 if ( empty( $feeds ) || ! $this->is_feed )
4235 return (bool) $this->is_feed;
4236 $qv = $this->get( 'feed' );
4237 if ( 'feed' == $qv )
4238 $qv = get_default_feed();
4239 return in_array( $qv, (array) $feeds );
4243 * Is the query for a comments feed?
4249 public function is_comment_feed() {
4250 return (bool) $this->is_comment_feed;
4254 * Is the query for the front page of the site?
4256 * This is for what is displayed at your site's main URL.
4258 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4260 * If you set a static page for the front page of your site, this function will return
4261 * true when viewing that page.
4263 * Otherwise the same as @see WP_Query::is_home()
4267 * @uses get_option()
4269 * @return bool True, if front of site.
4271 public function is_front_page() {
4273 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4275 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4282 * Is the query for the blog homepage?
4284 * This is the page which shows the time based blog content of your site.
4286 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4288 * If you set a static page for the front page of your site, this function will return
4289 * true only on the page you set as the "Posts page".
4291 * @see WP_Query::is_front_page()
4295 * @return bool True if blog view homepage.
4297 public function is_home() {
4298 return (bool) $this->is_home;
4302 * Is the query for an existing month archive?
4308 public function is_month() {
4309 return (bool) $this->is_month;
4313 * Is the query for an existing single page?
4315 * If the $page parameter is specified, this function will additionally
4316 * check if the query is for one of the pages specified.
4318 * @see WP_Query::is_single()
4319 * @see WP_Query::is_singular()
4323 * @param mixed $page Page ID, title, slug, path, or array of such.
4326 public function is_page( $page = '' ) {
4327 if ( !$this->is_page )
4330 if ( empty( $page ) )
4333 $page_obj = $this->get_queried_object();
4335 $page = (array) $page;
4337 if ( in_array( $page_obj->ID, $page ) ) {
4339 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4341 } else if ( in_array( $page_obj->post_name, $page ) ) {
4344 foreach ( $page as $pagepath ) {
4345 if ( ! strpos( $pagepath, '/' ) ) {
4348 $pagepath_obj = get_page_by_path( $pagepath );
4350 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4360 * Is the query for paged result and not for the first page?
4366 public function is_paged() {
4367 return (bool) $this->is_paged;
4371 * Is the query for a post or page preview?
4377 public function is_preview() {
4378 return (bool) $this->is_preview;
4382 * Is the query for the robots file?
4388 public function is_robots() {
4389 return (bool) $this->is_robots;
4393 * Is the query for a search?
4399 public function is_search() {
4400 return (bool) $this->is_search;
4404 * Is the query for an existing single post?
4406 * Works for any post type, except attachments and pages
4408 * If the $post parameter is specified, this function will additionally
4409 * check if the query is for one of the Posts specified.
4411 * @see WP_Query::is_page()
4412 * @see WP_Query::is_singular()
4416 * @param mixed $post Post ID, title, slug, path, or array of such.
4419 public function is_single( $post = '' ) {
4420 if ( !$this->is_single )
4426 $post_obj = $this->get_queried_object();
4428 $post = (array) $post;
4430 if ( in_array( $post_obj->ID, $post ) ) {
4432 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4434 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4437 foreach ( $post as $postpath ) {
4438 if ( ! strpos( $postpath, '/' ) ) {
4441 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4443 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4452 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4454 * If the $post_types parameter is specified, this function will additionally
4455 * check if the query is for one of the Posts Types specified.
4457 * @see WP_Query::is_page()
4458 * @see WP_Query::is_single()
4462 * @param mixed $post_types Optional. Post Type or array of Post Types
4465 public function is_singular( $post_types = '' ) {
4466 if ( empty( $post_types ) || !$this->is_singular )
4467 return (bool) $this->is_singular;
4469 $post_obj = $this->get_queried_object();
4471 return in_array( $post_obj->post_type, (array) $post_types );
4475 * Is the query for a specific time?
4481 public function is_time() {
4482 return (bool) $this->is_time;
4486 * Is the query for a trackback endpoint call?
4492 public function is_trackback() {
4493 return (bool) $this->is_trackback;
4497 * Is the query for an existing year archive?
4503 public function is_year() {
4504 return (bool) $this->is_year;
4508 * Is the query a 404 (returns no results)?
4514 public function is_404() {
4515 return (bool) $this->is_404;
4519 * Is the query the main query?
4525 public function is_main_query() {
4526 global $wp_the_query;
4527 return $wp_the_query === $this;
4531 * After looping through a nested query, this function
4532 * restores the $post global to the current post in this query.
4538 public function reset_postdata() {
4539 if ( ! empty( $this->post ) ) {
4540 $GLOBALS['post'] = $this->post;
4541 setup_postdata( $this->post );
4547 * Redirect old slugs to the correct permalink.
4549 * Attempts to find the current slug from the past slugs.
4555 * @return null If no link is found, null is returned.
4557 function wp_old_slug_redirect() {
4559 if ( is_404() && '' != $wp_query->query_vars['name'] ) :
4562 // Guess the current post_type based on the query vars.
4563 if ( get_query_var('post_type') )
4564 $post_type = get_query_var('post_type');
4565 elseif ( !empty($wp_query->query_vars['pagename']) )
4566 $post_type = 'page';
4568 $post_type = 'post';
4570 if ( is_array( $post_type ) ) {
4571 if ( count( $post_type ) > 1 )
4573 $post_type = array_shift( $post_type );
4576 // Do not attempt redirect for hierarchical post types
4577 if ( is_post_type_hierarchical( $post_type ) )
4580 $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']);
4582 // if year, monthnum, or day have been specified, make our query more precise
4583 // just in case there are multiple identical _wp_old_slug values
4584 if ( '' != $wp_query->query_vars['year'] )
4585 $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
4586 if ( '' != $wp_query->query_vars['monthnum'] )
4587 $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
4588 if ( '' != $wp_query->query_vars['day'] )
4589 $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
4591 $id = (int) $wpdb->get_var($query);
4596 $link = get_permalink($id);
4601 wp_redirect( $link, 301 ); // Permanent redirect
4607 * Set up global post data.
4611 * @param object $post Post data.
4612 * @uses do_action_ref_array() Calls 'the_post'
4613 * @return bool True when finished.
4615 function setup_postdata( $post ) {
4616 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4618 $id = (int) $post->ID;
4620 $authordata = get_userdata($post->post_author);
4622 $currentday = mysql2date('d.m.y', $post->post_date, false);
4623 $currentmonth = mysql2date('m', $post->post_date, false);
4626 $page = get_query_var('page');
4629 if ( is_single() || is_page() || is_feed() )
4631 $content = $post->post_content;
4632 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4635 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4636 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4637 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4638 // Ignore nextpage at the beginning of the content.
4639 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4640 $content = substr( $content, 15 );
4641 $pages = explode('<!--nextpage-->', $content);
4642 $numpages = count($pages);
4643 if ( $numpages > 1 )
4646 $pages = array( $post->post_content );
4650 * Fires once the post data has been setup.
4654 * @param WP_Post &$post The Post object (passed by reference).
4656 do_action_ref_array( 'the_post', array( &$post ) );