5 * The query API attempts to get which part of WordPress the user is on. It
6 * also provides functionality for getting URL query information.
8 * @link https://codex.wordpress.org/The_Loop More information on The Loop.
15 * Retrieve variable in the WP_Query class.
19 * @global WP_Query $wp_query
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 = '' ) {
27 return $wp_query->get( $var, $default );
31 * Retrieve the currently-queried object. Wrapper for $wp_query->get_queried_object()
36 * @global WP_Query $wp_query
40 function get_queried_object() {
42 return $wp_query->get_queried_object();
46 * Retrieve ID of the current queried object. Wrapper for $wp_query->get_queried_object_id()
51 * @global WP_Query $wp_query
55 function get_queried_object_id() {
57 return $wp_query->get_queried_object_id();
65 * @global WP_Query $wp_query
67 * @param string $var Query variable key.
70 function set_query_var( $var, $value ) {
72 $wp_query->set( $var, $value );
76 * Set up The Loop with query parameters.
78 * This will override the current WordPress Loop and shouldn't be used more than
79 * once. This must not be used within the WordPress Loop.
83 * @global WP_Query $wp_query
85 * @param string $query
86 * @return array List of posts
88 function query_posts($query) {
89 $GLOBALS['wp_query'] = new WP_Query();
90 return $GLOBALS['wp_query']->query($query);
94 * Destroy the previous query and set up a new query.
96 * This should be used after {@link query_posts()} and before another {@link
97 * query_posts()}. This will remove obscure bugs that occur when the previous
98 * wp_query object is not destroyed properly before another is set up.
102 * @global WP_Query $wp_query
103 * @global WP_Query $wp_the_query
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.
116 * @global WP_Query $wp_query
118 function wp_reset_postdata() {
121 if ( isset( $wp_query ) ) {
122 $wp_query->reset_postdata();
131 * Is the query for an existing archive page?
133 * Month, Year, Category, Author, Post Type archive...
137 * @global WP_Query $wp_query
141 function is_archive() {
144 if ( ! isset( $wp_query ) ) {
145 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
149 return $wp_query->is_archive();
153 * Is the query for an existing post type archive page?
157 * @global WP_Query $wp_query
159 * @param string|array $post_types Optional. Post type or array of posts types to check against.
162 function is_post_type_archive( $post_types = '' ) {
165 if ( ! isset( $wp_query ) ) {
166 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
170 return $wp_query->is_post_type_archive( $post_types );
174 * Is the query for an existing attachment page?
178 * @global WP_Query $wp_query
180 * @param int|string|array|object $attachment Attachment ID, title, slug, or array of such.
183 function is_attachment( $attachment = '' ) {
186 if ( ! isset( $wp_query ) ) {
187 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
191 return $wp_query->is_attachment( $attachment );
195 * Is the query for an existing author archive page?
197 * If the $author parameter is specified, this function will additionally
198 * check if the query is for one of the authors specified.
202 * @global WP_Query $wp_query
204 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
207 function is_author( $author = '' ) {
210 if ( ! isset( $wp_query ) ) {
211 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
215 return $wp_query->is_author( $author );
219 * Is the query for an existing category archive page?
221 * If the $category parameter is specified, this function will additionally
222 * check if the query is for one of the categories specified.
226 * @global WP_Query $wp_query
228 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
231 function is_category( $category = '' ) {
234 if ( ! isset( $wp_query ) ) {
235 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
239 return $wp_query->is_category( $category );
243 * Is the query for an existing tag archive page?
245 * If the $tag parameter is specified, this function will additionally
246 * check if the query is for one of the tags specified.
250 * @global WP_Query $wp_query
252 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
255 function is_tag( $tag = '' ) {
258 if ( ! isset( $wp_query ) ) {
259 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
263 return $wp_query->is_tag( $tag );
267 * Is the query for an existing taxonomy archive page?
269 * If the $taxonomy parameter is specified, this function will additionally
270 * check if the query is for that specific $taxonomy.
272 * If the $term parameter is specified in addition to the $taxonomy parameter,
273 * this function will additionally check if the query is for one of the terms
278 * @global WP_Query $wp_query
280 * @param string|array $taxonomy Optional. Taxonomy slug or slugs.
281 * @param int|string|array $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
284 function is_tax( $taxonomy = '', $term = '' ) {
287 if ( ! isset( $wp_query ) ) {
288 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
292 return $wp_query->is_tax( $taxonomy, $term );
296 * Whether the current URL is within the comments popup window.
300 * @global WP_Query $wp_query
304 function is_comments_popup() {
307 if ( ! isset( $wp_query ) ) {
308 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
312 return $wp_query->is_comments_popup();
316 * Is the query for an existing date archive?
320 * @global WP_Query $wp_query
327 if ( ! isset( $wp_query ) ) {
328 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
332 return $wp_query->is_date();
336 * Is the query for an existing day archive?
340 * @global WP_Query $wp_query
347 if ( ! isset( $wp_query ) ) {
348 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
352 return $wp_query->is_day();
356 * Is the query for a feed?
360 * @global WP_Query $wp_query
362 * @param string|array $feeds Optional feed types to check.
365 function is_feed( $feeds = '' ) {
368 if ( ! isset( $wp_query ) ) {
369 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
373 return $wp_query->is_feed( $feeds );
377 * Is the query for a comments feed?
381 * @global WP_Query $wp_query
385 function is_comment_feed() {
388 if ( ! isset( $wp_query ) ) {
389 _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
393 return $wp_query->is_comment_feed();
397 * Is the query for the front page of the site?
399 * This is for what is displayed at your site's main URL.
401 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
403 * If you set a static page for the front page of your site, this function will return
404 * true when viewing that page.
406 * Otherwise the same as @see is_home()
410 * @global WP_Query $wp_query
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()
439 * @global WP_Query $wp_query
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?
459 * @global WP_Query $wp_query
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.
485 * @global WP_Query $wp_query
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?
506 * @global WP_Query $wp_query
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?
526 * @global WP_Query $wp_query
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?
546 * @global WP_Query $wp_query
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?
566 * @global WP_Query $wp_query
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.
594 * @global WP_Query $wp_query
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.
621 * @global WP_Query $wp_query
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?
642 * @global WP_Query $wp_query
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?
662 * @global WP_Query $wp_query
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?
682 * @global WP_Query $wp_query
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)?
702 * @global WP_Query $wp_query
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?
722 * @global WP_Query $wp_query
726 function is_main_query() {
727 if ( 'pre_get_posts' === current_filter() ) {
728 $message = sprintf( __( 'In <code>%1$s</code>, use the <code>%2$s</code> method, not the <code>%3$s</code> function. See %4$s.' ),
729 'pre_get_posts', 'WP_Query::is_main_query()', 'is_main_query()', __( 'https://codex.wordpress.org/Function_Reference/is_main_query' ) );
730 _doing_it_wrong( __FUNCTION__, $message, '3.7' );
734 return $wp_query->is_main_query();
738 * The Loop. Post loop control.
742 * Whether current WordPress query has results to loop over.
746 * @global WP_Query $wp_query
750 function have_posts() {
752 return $wp_query->have_posts();
756 * Whether the caller is in the Loop.
760 * @global WP_Query $wp_query
762 * @return bool True if caller is within loop, false if loop hasn't started or ended.
764 function in_the_loop() {
766 return $wp_query->in_the_loop;
770 * Rewind the loop posts.
774 * @global WP_Query $wp_query
776 function rewind_posts() {
778 $wp_query->rewind_posts();
782 * Iterate the post index in the loop.
786 * @global WP_Query $wp_query
788 function the_post() {
790 $wp_query->the_post();
798 * Whether there are comments to loop over.
802 * @global WP_Query $wp_query
806 function have_comments() {
808 return $wp_query->have_comments();
812 * Iterate comment index in the comment loop.
816 * @global WP_Query $wp_query
820 function the_comment() {
822 return $wp_query->the_comment();
830 * The WordPress Query class.
832 * @link https://codex.wordpress.org/Function_Reference/WP_Query Codex page.
839 * Query vars set by the user
848 * Query vars, after parsing
854 public $query_vars = array();
857 * Taxonomy query, as passed to get_tax_sql()
861 * @var object WP_Tax_Query
866 * Metadata query container
870 * @var object WP_Meta_Query
872 public $meta_query = false;
875 * Date query container
879 * @var object WP_Date_Query
881 public $date_query = false;
884 * Holds the data for a single object that is queried.
886 * Holds the contents of a post, page, category, attachment.
892 public $queried_object;
895 * The ID of the queried object.
901 public $queried_object_id;
904 * Get post database query.
922 * The amount of posts for the current query.
928 public $post_count = 0;
931 * Index of the current item in the loop.
937 public $current_post = -1;
940 * Whether the loop has started and the caller is in the loop.
946 public $in_the_loop = false;
958 * The list of comments for current post.
967 * The amount of comments for the posts.
973 public $comment_count = 0;
976 * The index of the comment in the comment loop.
982 public $current_comment = -1;
985 * Current comment ID.
994 * The amount of found posts for the current query.
996 * If limit clause was not used, equals $post_count.
1002 public $found_posts = 0;
1005 * The amount of pages.
1011 public $max_num_pages = 0;
1014 * The amount of comment pages.
1020 public $max_num_comment_pages = 0;
1023 * Set if query is single post.
1029 public $is_single = false;
1032 * Set if query is preview of blog.
1038 public $is_preview = false;
1041 * Set if query returns a page.
1047 public $is_page = false;
1050 * Set if query is an archive list.
1056 public $is_archive = false;
1059 * Set if query is part of a date.
1065 public $is_date = false;
1068 * Set if query contains a year.
1074 public $is_year = false;
1077 * Set if query contains a month.
1083 public $is_month = false;
1086 * Set if query contains a day.
1092 public $is_day = false;
1095 * Set if query contains time.
1101 public $is_time = false;
1104 * Set if query contains an author.
1110 public $is_author = false;
1113 * Set if query contains category.
1119 public $is_category = false;
1122 * Set if query contains tag.
1128 public $is_tag = false;
1131 * Set if query contains taxonomy.
1137 public $is_tax = false;
1140 * Set if query was part of a search result.
1146 public $is_search = false;
1149 * Set if query is feed display.
1155 public $is_feed = false;
1158 * Set if query is comment feed display.
1164 public $is_comment_feed = false;
1167 * Set if query is trackback.
1173 public $is_trackback = false;
1176 * Set if query is blog homepage.
1182 public $is_home = false;
1185 * Set if query couldn't found anything.
1191 public $is_404 = false;
1194 * Set if query is within comments popup window.
1200 public $is_comments_popup = false;
1203 * Set if query is paged
1209 public $is_paged = false;
1212 * Set if query is part of administration page.
1218 public $is_admin = false;
1221 * Set if query is an attachment.
1227 public $is_attachment = false;
1230 * Set if is single, is a page, or is an attachment.
1236 public $is_singular = false;
1239 * Set if query is for robots.
1245 public $is_robots = false;
1248 * Set if query contains posts.
1250 * Basically, the homepage if the option isn't set for the static homepage.
1256 public $is_posts_page = false;
1259 * Set if query is for a post type archive.
1265 public $is_post_type_archive = false;
1268 * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
1269 * whether we have to re-parse because something has changed
1275 private $query_vars_hash = false;
1278 * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
1279 * via pre_get_posts hooks.
1284 private $query_vars_changed = true;
1287 * Set if post thumbnails are cached
1293 public $thumbnails_cached = false;
1296 * Cached list of search stopwords.
1303 private $compat_fields = array( 'query_vars_hash', 'query_vars_changed' );
1305 private $compat_methods = array( 'init_query_flags', 'parse_tax_query' );
1308 * Resets query flags to false.
1310 * The query flags are what page info WordPress was able to figure out.
1315 private function init_query_flags() {
1316 $this->is_single = false;
1317 $this->is_preview = false;
1318 $this->is_page = false;
1319 $this->is_archive = false;
1320 $this->is_date = false;
1321 $this->is_year = false;
1322 $this->is_month = false;
1323 $this->is_day = false;
1324 $this->is_time = false;
1325 $this->is_author = false;
1326 $this->is_category = false;
1327 $this->is_tag = false;
1328 $this->is_tax = false;
1329 $this->is_search = false;
1330 $this->is_feed = false;
1331 $this->is_comment_feed = false;
1332 $this->is_trackback = false;
1333 $this->is_home = false;
1334 $this->is_404 = false;
1335 $this->is_comments_popup = false;
1336 $this->is_paged = false;
1337 $this->is_admin = false;
1338 $this->is_attachment = false;
1339 $this->is_singular = false;
1340 $this->is_robots = false;
1341 $this->is_posts_page = false;
1342 $this->is_post_type_archive = false;
1346 * Initiates object properties and sets default values.
1351 public function init() {
1352 unset($this->posts);
1353 unset($this->query);
1354 $this->query_vars = array();
1355 unset($this->queried_object);
1356 unset($this->queried_object_id);
1357 $this->post_count = 0;
1358 $this->current_post = -1;
1359 $this->in_the_loop = false;
1360 unset( $this->request );
1361 unset( $this->post );
1362 unset( $this->comments );
1363 unset( $this->comment );
1364 $this->comment_count = 0;
1365 $this->current_comment = -1;
1366 $this->found_posts = 0;
1367 $this->max_num_pages = 0;
1368 $this->max_num_comment_pages = 0;
1370 $this->init_query_flags();
1374 * Reparse the query vars.
1379 public function parse_query_vars() {
1380 $this->parse_query();
1384 * Fills in the query variables, which do not exist within the parameter.
1389 * @param array $array Defined query variables.
1390 * @return array Complete query variables with undefined ones filled in empty.
1392 public function fill_query_vars($array) {
1432 foreach ( $keys as $key ) {
1433 if ( !isset($array[$key]) )
1437 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in',
1438 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
1439 'author__in', 'author__not_in' );
1441 foreach ( $array_keys as $key ) {
1442 if ( !isset($array[$key]) )
1443 $array[$key] = array();
1449 * Parse a query string and set query type booleans.
1452 * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
1453 * array key to `$orderby`.
1456 * @param string|array $query {
1457 * Optional. Array or string of Query parameters.
1459 * @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
1460 * @type int|string $author Author ID, or comma-separated list of IDs.
1461 * @type string $author_name User 'user_nicename'.
1462 * @type array $author__in An array of author IDs to query from.
1463 * @type array $author__not_in An array of author IDs not to query from.
1464 * @type bool $cache_results Whether to cache post information. Default true.
1465 * @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
1466 * @type array $category__and An array of category IDs (AND in).
1467 * @type array $category__in An array of category IDs (OR in, no children).
1468 * @type array $category__not_in An array of category IDs (NOT in).
1469 * @type string $category_name Use category slug (not name, this or any children).
1470 * @type int $comments_per_page The number of comments to return per page.
1471 * Default 'comments_per_page' option.
1472 * @type int|string $comments_popup Whether the query is within the comments popup. Default empty.
1473 * @type array $date_query An associative array of WP_Date_Query arguments.
1474 * {@see WP_Date_Query::__construct()}
1475 * @type int $day Day of the month. Default empty. Accepts numbers 1-31.
1476 * @type bool $exact Whether to search by exact keyword. Default false.
1477 * @type string|array $fields Which fields to return. Single field or all fields (string),
1478 * or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
1479 * Default all fields. Accepts 'ids', 'id=>parent'.
1480 * @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
1481 * @type int|bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
1482 * excludes stickies from 'post__in'. Accepts 1|true, 0|false.
1484 * @type int $m Combination YearMonth. Accepts any four-digit year and month
1485 * numbers 1-12. Default empty.
1486 * @type string $meta_compare Comparison operator to test the 'meta_value'.
1487 * @type string $meta_key Custom field key.
1488 * @type array $meta_query An associative array of WP_Meta_Query arguments.
1489 * {@see WP_Meta_Query->queries}
1490 * @type string $meta_value Custom field value.
1491 * @type int $meta_value_num Custom field value number.
1492 * @type int $menu_order The menu order of the posts.
1493 * @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
1494 * @type string $name Post slug.
1495 * @type bool $nopaging Show all posts (true) or paginate (false). Default false.
1496 * @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
1497 * performance. Default false.
1498 * @type int $offset The number of posts to offset before retrieval.
1499 * @type string $order Designates ascending or descending order of posts. Default 'DESC'.
1500 * Accepts 'ASC', 'DESC'.
1501 * @type string|array $orderby Sort retrieved posts by parameter. One or more options may be
1502 * passed. To use 'meta_value', or 'meta_value_num',
1503 * 'meta_key=keyname' must be also be defined. To sort by a
1504 * specific `$meta_query` clause, use that clause's array key.
1505 * Default 'date'. Accepts 'none', 'name', 'author', 'date',
1506 * 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand',
1507 * 'comment_count', 'meta_value', 'meta_value_num', and the
1508 * array keys of `$meta_query`.
1509 * @type int $p Post ID.
1510 * @type int $page Show the number of posts that would show up on page X of a
1511 * static front page.
1512 * @type int $paged The number of the current page.
1513 * @type int $page_id Page ID.
1514 * @type string $pagename Page slug.
1515 * @type string $perm Show posts if user has the appropriate capability.
1516 * @type array $post__in An array of post IDs to retrieve, sticky posts will be included
1517 * @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
1518 * @type array $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
1519 * separated IDs will NOT work.
1520 * @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
1522 * @type array $post_parent__in An array containing parent page IDs to query child pages from.
1523 * @type array $post_parent__not_in An array containing parent page IDs not to query child pages from.
1524 * @type string|array $post_type A post type slug (string) or array of post type slugs.
1525 * Default 'any' if using 'tax_query'.
1526 * @type string|array $post_status A post status (string) or array of post statuses.
1527 * @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
1528 * @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
1529 * 'posts_per_page' when is_archive(), or is_search() are true.
1530 * @type string $s Search keyword.
1531 * @type int $second Second of the minute. Default empty. Accepts numbers 0-60.
1532 * @type array $search_terms Array of search terms.
1533 * @type bool $sentence Whether to search by phrase. Default false.
1534 * @type bool $suppress_filters Whether to suppress filters. Default false.
1535 * @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
1536 * @type array $tag__and An array of tag ids (AND in).
1537 * @type array $tag__in An array of tag ids (OR in).
1538 * @type array $tag__not_in An array of tag ids (NOT in).
1539 * @type int $tag_id Tag id or comma-separated list of IDs.
1540 * @type array $tag_slug__and An array of tag slugs (AND in).
1541 * @type array $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
1542 * true. Note: a string of comma-separated IDs will NOT work.
1543 * @type array $tax_query An associative array of WP_Tax_Query arguments.
1544 * {@see WP_Tax_Query->queries}
1545 * @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
1546 * @type bool $update_post_term_cache Whether to update the post term cache. Default true.
1547 * @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
1548 * @type int $year The four-digit year. Default empty. Accepts any four-digit year.
1551 public function parse_query( $query = '' ) {
1552 if ( ! empty( $query ) ) {
1554 $this->query = $this->query_vars = wp_parse_args( $query );
1555 } elseif ( ! isset( $this->query ) ) {
1556 $this->query = $this->query_vars;
1559 $this->query_vars = $this->fill_query_vars($this->query_vars);
1560 $qv = &$this->query_vars;
1561 $this->query_vars_changed = true;
1563 if ( ! empty($qv['robots']) )
1564 $this->is_robots = true;
1566 $qv['p'] = absint($qv['p']);
1567 $qv['page_id'] = absint($qv['page_id']);
1568 $qv['year'] = absint($qv['year']);
1569 $qv['monthnum'] = absint($qv['monthnum']);
1570 $qv['day'] = absint($qv['day']);
1571 $qv['w'] = absint($qv['w']);
1572 $qv['m'] = preg_replace( '|[^0-9]|', '', $qv['m'] );
1573 $qv['paged'] = absint($qv['paged']);
1574 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1575 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
1576 $qv['pagename'] = trim( $qv['pagename'] );
1577 $qv['name'] = trim( $qv['name'] );
1578 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1579 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1580 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1581 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
1583 // Fairly insane upper bound for search string lengths.
1584 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
1588 // Compat. Map subpost to attachment.
1589 if ( '' != $qv['subpost'] )
1590 $qv['attachment'] = $qv['subpost'];
1591 if ( '' != $qv['subpost_id'] )
1592 $qv['attachment_id'] = $qv['subpost_id'];
1594 $qv['attachment_id'] = absint($qv['attachment_id']);
1596 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1597 $this->is_single = true;
1598 $this->is_attachment = true;
1599 } elseif ( '' != $qv['name'] ) {
1600 $this->is_single = true;
1601 } elseif ( $qv['p'] ) {
1602 $this->is_single = true;
1603 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1604 // If year, month, day, hour, minute, and second are set, a single
1605 // post is being queried.
1606 $this->is_single = true;
1607 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1608 $this->is_page = true;
1609 $this->is_single = false;
1611 // Look for archive queries. Dates, categories, authors, search, post type archives.
1613 if ( isset( $this->query['s'] ) ) {
1614 $this->is_search = true;
1617 if ( '' !== $qv['second'] ) {
1618 $this->is_time = true;
1619 $this->is_date = true;
1622 if ( '' !== $qv['minute'] ) {
1623 $this->is_time = true;
1624 $this->is_date = true;
1627 if ( '' !== $qv['hour'] ) {
1628 $this->is_time = true;
1629 $this->is_date = true;
1633 if ( ! $this->is_date ) {
1634 $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
1635 if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
1636 $qv['error'] = '404';
1638 $this->is_day = true;
1639 $this->is_date = true;
1644 if ( $qv['monthnum'] ) {
1645 if ( ! $this->is_date ) {
1646 if ( 12 < $qv['monthnum'] ) {
1647 $qv['error'] = '404';
1649 $this->is_month = true;
1650 $this->is_date = true;
1655 if ( $qv['year'] ) {
1656 if ( ! $this->is_date ) {
1657 $this->is_year = true;
1658 $this->is_date = true;
1663 $this->is_date = true;
1664 if ( strlen($qv['m']) > 9 ) {
1665 $this->is_time = true;
1666 } elseif ( strlen( $qv['m'] ) > 7 ) {
1667 $this->is_day = true;
1668 } elseif ( strlen( $qv['m'] ) > 5 ) {
1669 $this->is_month = true;
1671 $this->is_year = true;
1675 if ( '' != $qv['w'] ) {
1676 $this->is_date = true;
1679 $this->query_vars_hash = false;
1680 $this->parse_tax_query( $qv );
1682 foreach ( $this->tax_query->queries as $tax_query ) {
1683 if ( ! is_array( $tax_query ) ) {
1687 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
1688 switch ( $tax_query['taxonomy'] ) {
1690 $this->is_category = true;
1693 $this->is_tag = true;
1696 $this->is_tax = true;
1700 unset( $tax_query );
1702 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1703 $this->is_author = false;
1705 $this->is_author = true;
1708 if ( '' != $qv['author_name'] )
1709 $this->is_author = true;
1711 if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
1712 $post_type_obj = get_post_type_object( $qv['post_type'] );
1713 if ( ! empty( $post_type_obj->has_archive ) )
1714 $this->is_post_type_archive = true;
1717 if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
1718 $this->is_archive = true;
1721 if ( '' != $qv['feed'] )
1722 $this->is_feed = true;
1724 if ( '' != $qv['tb'] )
1725 $this->is_trackback = true;
1727 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
1728 $this->is_paged = true;
1730 if ( '' != $qv['comments_popup'] )
1731 $this->is_comments_popup = true;
1733 // if we're previewing inside the write screen
1734 if ( '' != $qv['preview'] )
1735 $this->is_preview = true;
1738 $this->is_admin = true;
1740 if ( false !== strpos($qv['feed'], 'comments-') ) {
1741 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1742 $qv['withcomments'] = 1;
1745 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1747 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1748 $this->is_comment_feed = true;
1750 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 ) )
1751 $this->is_home = true;
1753 // Correct is_* for page_on_front and page_for_posts
1754 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1755 $_query = wp_parse_args($this->query);
1756 // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
1757 if ( isset($_query['pagename']) && '' == $_query['pagename'] )
1758 unset($_query['pagename']);
1759 if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
1760 $this->is_page = true;
1761 $this->is_home = false;
1762 $qv['page_id'] = get_option('page_on_front');
1763 // Correct <!--nextpage--> for page_on_front
1764 if ( !empty($qv['paged']) ) {
1765 $qv['page'] = $qv['paged'];
1766 unset($qv['paged']);
1771 if ( '' != $qv['pagename'] ) {
1772 $this->queried_object = get_page_by_path($qv['pagename']);
1773 if ( !empty($this->queried_object) )
1774 $this->queried_object_id = (int) $this->queried_object->ID;
1776 unset($this->queried_object);
1778 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1779 $this->is_page = false;
1780 $this->is_home = true;
1781 $this->is_posts_page = true;
1785 if ( $qv['page_id'] ) {
1786 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1787 $this->is_page = false;
1788 $this->is_home = true;
1789 $this->is_posts_page = true;
1793 if ( !empty($qv['post_type']) ) {
1794 if ( is_array($qv['post_type']) )
1795 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1797 $qv['post_type'] = sanitize_key($qv['post_type']);
1800 if ( ! empty( $qv['post_status'] ) ) {
1801 if ( is_array( $qv['post_status'] ) )
1802 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1804 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1807 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1808 $this->is_comment_feed = false;
1810 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1811 // Done correcting is_* for page_on_front and page_for_posts
1813 if ( '404' == $qv['error'] )
1816 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1817 $this->query_vars_changed = false;
1820 * Fires after the main query vars have been parsed.
1824 * @param WP_Query &$this The WP_Query instance (passed by reference).
1826 do_action_ref_array( 'parse_query', array( &$this ) );
1830 * Parses various taxonomy related query vars.
1832 * For BC, this method is not marked as protected. See [28987].
1837 * @param array &$q The query variables
1839 public function parse_tax_query( &$q ) {
1840 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1841 $tax_query = $q['tax_query'];
1843 $tax_query = array();
1846 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1847 $tax_query[] = array(
1848 'taxonomy' => $q['taxonomy'],
1849 'terms' => array( $q['term'] ),
1854 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1855 if ( 'post_tag' == $taxonomy )
1856 continue; // Handled further down in the $q['tag'] block
1858 if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1859 $tax_query_defaults = array(
1860 'taxonomy' => $taxonomy,
1864 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1865 $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1868 $term = $q[$t->query_var];
1870 if ( is_array( $term ) ) {
1871 $term = implode( ',', $term );
1874 if ( strpos($term, '+') !== false ) {
1875 $terms = preg_split( '/[+]+/', $term );
1876 foreach ( $terms as $term ) {
1877 $tax_query[] = array_merge( $tax_query_defaults, array(
1878 'terms' => array( $term )
1882 $tax_query[] = array_merge( $tax_query_defaults, array(
1883 'terms' => preg_split( '/[,]+/', $term )
1890 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1891 $cat_in = $cat_not_in = array();
1893 $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1894 $cat_array = array_map( 'intval', $cat_array );
1895 $q['cat'] = implode( ',', $cat_array );
1897 foreach ( $cat_array as $cat ) {
1901 $cat_not_in[] = abs( $cat );
1904 if ( ! empty( $cat_in ) ) {
1905 $tax_query[] = array(
1906 'taxonomy' => 'category',
1908 'field' => 'term_id',
1909 'include_children' => true
1913 if ( ! empty( $cat_not_in ) ) {
1914 $tax_query[] = array(
1915 'taxonomy' => 'category',
1916 'terms' => $cat_not_in,
1917 'field' => 'term_id',
1918 'operator' => 'NOT IN',
1919 'include_children' => true
1922 unset( $cat_array, $cat_in, $cat_not_in );
1925 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1926 $q['category__and'] = (array) $q['category__and'];
1927 if ( ! isset( $q['category__in'] ) )
1928 $q['category__in'] = array();
1929 $q['category__in'][] = absint( reset( $q['category__and'] ) );
1930 unset( $q['category__and'] );
1933 if ( ! empty( $q['category__in'] ) ) {
1934 $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1935 $tax_query[] = array(
1936 'taxonomy' => 'category',
1937 'terms' => $q['category__in'],
1938 'field' => 'term_id',
1939 'include_children' => false
1943 if ( ! empty($q['category__not_in']) ) {
1944 $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
1945 $tax_query[] = array(
1946 'taxonomy' => 'category',
1947 'terms' => $q['category__not_in'],
1948 'operator' => 'NOT IN',
1949 'include_children' => false
1953 if ( ! empty($q['category__and']) ) {
1954 $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
1955 $tax_query[] = array(
1956 'taxonomy' => 'category',
1957 'terms' => $q['category__and'],
1958 'field' => 'term_id',
1959 'operator' => 'AND',
1960 'include_children' => false
1965 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
1966 if ( strpos($q['tag'], ',') !== false ) {
1967 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
1968 foreach ( (array) $tags as $tag ) {
1969 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1970 $q['tag_slug__in'][] = $tag;
1972 } elseif ( preg_match('/[+\r\n\t ]+/', $q['tag'] ) || ! empty( $q['cat'] ) ) {
1973 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
1974 foreach ( (array) $tags as $tag ) {
1975 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1976 $q['tag_slug__and'][] = $tag;
1979 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1980 $q['tag_slug__in'][] = $q['tag'];
1984 if ( !empty($q['tag_id']) ) {
1985 $q['tag_id'] = absint( $q['tag_id'] );
1986 $tax_query[] = array(
1987 'taxonomy' => 'post_tag',
1988 'terms' => $q['tag_id']
1992 if ( !empty($q['tag__in']) ) {
1993 $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
1994 $tax_query[] = array(
1995 'taxonomy' => 'post_tag',
1996 'terms' => $q['tag__in']
2000 if ( !empty($q['tag__not_in']) ) {
2001 $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
2002 $tax_query[] = array(
2003 'taxonomy' => 'post_tag',
2004 'terms' => $q['tag__not_in'],
2005 'operator' => 'NOT IN'
2009 if ( !empty($q['tag__and']) ) {
2010 $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
2011 $tax_query[] = array(
2012 'taxonomy' => 'post_tag',
2013 'terms' => $q['tag__and'],
2018 if ( !empty($q['tag_slug__in']) ) {
2019 $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
2020 $tax_query[] = array(
2021 'taxonomy' => 'post_tag',
2022 'terms' => $q['tag_slug__in'],
2027 if ( !empty($q['tag_slug__and']) ) {
2028 $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
2029 $tax_query[] = array(
2030 'taxonomy' => 'post_tag',
2031 'terms' => $q['tag_slug__and'],
2037 $this->tax_query = new WP_Tax_Query( $tax_query );
2040 * Fires after taxonomy-related query vars have been parsed.
2044 * @param WP_Query $this The WP_Query instance.
2046 do_action( 'parse_tax_query', $this );
2050 * Generate SQL for the WHERE clause based on passed search terms.
2054 * @global wpdb $wpdb
2055 * @param array $q Query variables.
2056 * @return string WHERE clause.
2058 protected function parse_search( &$q ) {
2063 // added slashes screw with quote grouping when done early, so done later
2064 $q['s'] = stripslashes( $q['s'] );
2065 if ( empty( $_GET['s'] ) && $this->is_main_query() )
2066 $q['s'] = urldecode( $q['s'] );
2067 // there are no line breaks in <input /> fields
2068 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
2069 $q['search_terms_count'] = 1;
2070 if ( ! empty( $q['sentence'] ) ) {
2071 $q['search_terms'] = array( $q['s'] );
2073 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
2074 $q['search_terms_count'] = count( $matches[0] );
2075 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
2076 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
2077 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
2078 $q['search_terms'] = array( $q['s'] );
2080 $q['search_terms'] = array( $q['s'] );
2084 $n = ! empty( $q['exact'] ) ? '' : '%';
2086 $q['search_orderby_title'] = array();
2087 foreach ( $q['search_terms'] as $term ) {
2089 $like = '%' . $wpdb->esc_like( $term ) . '%';
2090 $q['search_orderby_title'][] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $like );
2093 $like = $n . $wpdb->esc_like( $term ) . $n;
2094 $search .= $wpdb->prepare( "{$searchand}(($wpdb->posts.post_title LIKE %s) OR ($wpdb->posts.post_content LIKE %s))", $like, $like );
2095 $searchand = ' AND ';
2098 if ( ! empty( $search ) ) {
2099 $search = " AND ({$search}) ";
2100 if ( ! is_user_logged_in() )
2101 $search .= " AND ($wpdb->posts.post_password = '') ";
2108 * Check if the terms are suitable for searching.
2110 * Uses an array of stopwords (terms) that are excluded from the separate
2111 * term matching when searching for posts. The list of English stopwords is
2112 * the approximate search engines list, and is translatable.
2116 * @param array $terms Terms to check.
2117 * @return array Terms that are not stopwords.
2119 protected function parse_search_terms( $terms ) {
2120 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
2123 $stopwords = $this->get_search_stopwords();
2125 foreach ( $terms as $term ) {
2126 // keep before/after spaces when term is for exact match
2127 if ( preg_match( '/^".+"$/', $term ) )
2128 $term = trim( $term, "\"'" );
2130 $term = trim( $term, "\"' " );
2132 // Avoid single A-Z.
2133 if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z]$/i', $term ) ) )
2136 if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
2146 * Retrieve stopwords used when parsing search terms.
2150 * @return array Stopwords.
2152 protected function get_search_stopwords() {
2153 if ( isset( $this->stopwords ) )
2154 return $this->stopwords;
2156 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
2157 * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
2158 * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
2160 $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',
2161 'Comma-separated list of search stopwords in your language' ) );
2163 $stopwords = array();
2164 foreach( $words as $word ) {
2165 $word = trim( $word, "\r\n\t " );
2167 $stopwords[] = $word;
2171 * Filter stopwords used when parsing search terms.
2175 * @param array $stopwords Stopwords.
2177 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
2178 return $this->stopwords;
2182 * Generate SQL for the ORDER BY condition based on passed search terms.
2184 * @global wpdb $wpdb
2186 * @param array $q Query variables.
2187 * @return string ORDER BY clause.
2189 protected function parse_search_order( &$q ) {
2192 if ( $q['search_terms_count'] > 1 ) {
2193 $num_terms = count( $q['search_orderby_title'] );
2194 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
2196 $search_orderby = '(CASE ';
2197 // sentence match in 'post_title'
2198 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_title LIKE %s THEN 1 ", $like );
2200 // sanity limit, sort as sentence when more than 6 terms
2201 // (few searches are longer than 6 terms and most titles are not)
2202 if ( $num_terms < 7 ) {
2203 // all words in title
2204 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
2205 // any word in title, not needed when $num_terms == 1
2206 if ( $num_terms > 1 )
2207 $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
2210 // sentence match in 'post_content'
2211 $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 4 ", $like );
2212 $search_orderby .= 'ELSE 5 END)';
2214 // single word or sentence search
2215 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
2218 return $search_orderby;
2222 * If the passed orderby value is allowed, convert the alias to a
2223 * properly-prefixed orderby value.
2228 * @global wpdb $wpdb WordPress database abstraction object.
2230 * @param string $orderby Alias for the field to order by.
2231 * @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
2233 protected function parse_orderby( $orderby ) {
2236 // Used to filter values.
2237 $allowed_keys = array(
2238 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
2239 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
2240 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
2243 $primary_meta_key = '';
2244 $primary_meta_query = false;
2245 $meta_clauses = $this->meta_query->get_clauses();
2246 if ( ! empty( $meta_clauses ) ) {
2247 $primary_meta_query = reset( $meta_clauses );
2249 if ( ! empty( $primary_meta_query['key'] ) ) {
2250 $primary_meta_key = $primary_meta_query['key'];
2251 $allowed_keys[] = $primary_meta_key;
2254 $allowed_keys[] = 'meta_value';
2255 $allowed_keys[] = 'meta_value_num';
2256 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
2259 if ( ! in_array( $orderby, $allowed_keys ) ) {
2263 switch ( $orderby ) {
2268 case 'post_modified':
2273 case 'comment_count':
2274 $orderby_clause = "$wpdb->posts.{$orderby}";
2277 $orderby_clause = 'RAND()';
2279 case $primary_meta_key:
2281 if ( ! empty( $primary_meta_query['type'] ) ) {
2282 $orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
2284 $orderby_clause = "{$primary_meta_query['alias']}.meta_value";
2287 case 'meta_value_num':
2288 $orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
2291 if ( array_key_exists( $orderby, $meta_clauses ) ) {
2292 // $orderby corresponds to a meta_query clause.
2293 $meta_clause = $meta_clauses[ $orderby ];
2294 $orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
2296 // Default: order by post field.
2297 $orderby_clause = "$wpdb->posts.post_" . sanitize_key( $orderby );
2303 return $orderby_clause;
2307 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
2312 * @param string $order The 'order' query variable.
2313 * @return string The sanitized 'order' query variable.
2315 protected function parse_order( $order ) {
2316 if ( ! is_string( $order ) || empty( $order ) ) {
2320 if ( 'ASC' === strtoupper( $order ) ) {
2328 * Sets the 404 property and saves whether query is feed.
2333 public function set_404() {
2334 $is_feed = $this->is_feed;
2336 $this->init_query_flags();
2337 $this->is_404 = true;
2339 $this->is_feed = $is_feed;
2343 * Retrieve query variable.
2348 * @param string $query_var Query variable key.
2349 * @param mixed $default Value to return if the query variable is not set. Default ''.
2352 public function get( $query_var, $default = '' ) {
2353 if ( isset( $this->query_vars[ $query_var ] ) ) {
2354 return $this->query_vars[ $query_var ];
2361 * Set query variable.
2366 * @param string $query_var Query variable key.
2367 * @param mixed $value Query variable value.
2369 public function set($query_var, $value) {
2370 $this->query_vars[$query_var] = $value;
2374 * Retrieve the posts based on query variables.
2376 * There are a few filters and actions that can be used to modify the post
2382 * @global wpdb $wpdb
2384 * @return array List of posts.
2386 public function get_posts() {
2389 $this->parse_query();
2392 * Fires after the query variable object is created, but before the actual query is run.
2394 * Note: If using conditional tags, use the method versions within the passed instance
2395 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
2396 * like is_main_query() test against the global $wp_query instance, not the passed one.
2400 * @param WP_Query &$this The WP_Query instance (passed by reference).
2402 do_action_ref_array( 'pre_get_posts', array( &$this ) );
2405 $q = &$this->query_vars;
2407 // Fill again in case pre_get_posts unset some vars.
2408 $q = $this->fill_query_vars($q);
2411 $this->meta_query = new WP_Meta_Query();
2412 $this->meta_query->parse_query_vars( $q );
2414 // Set a flag if a pre_get_posts hook changed the query vars.
2415 $hash = md5( serialize( $this->query_vars ) );
2416 if ( $hash != $this->query_vars_hash ) {
2417 $this->query_vars_changed = true;
2418 $this->query_vars_hash = $hash;
2422 // First let's clear some variables
2425 $whichmimetype = '';
2431 $post_status_join = false;
2434 if ( isset( $q['caller_get_posts'] ) ) {
2435 _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
2436 if ( !isset( $q['ignore_sticky_posts'] ) )
2437 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
2440 if ( !isset( $q['ignore_sticky_posts'] ) )
2441 $q['ignore_sticky_posts'] = false;
2443 if ( !isset($q['suppress_filters']) )
2444 $q['suppress_filters'] = false;
2446 if ( !isset($q['cache_results']) ) {
2447 if ( wp_using_ext_object_cache() )
2448 $q['cache_results'] = false;
2450 $q['cache_results'] = true;
2453 if ( !isset($q['update_post_term_cache']) )
2454 $q['update_post_term_cache'] = true;
2456 if ( !isset($q['update_post_meta_cache']) )
2457 $q['update_post_meta_cache'] = true;
2459 if ( !isset($q['post_type']) ) {
2460 if ( $this->is_search )
2461 $q['post_type'] = 'any';
2463 $q['post_type'] = '';
2465 $post_type = $q['post_type'];
2466 if ( empty( $q['posts_per_page'] ) ) {
2467 $q['posts_per_page'] = get_option( 'posts_per_page' );
2469 if ( isset($q['showposts']) && $q['showposts'] ) {
2470 $q['showposts'] = (int) $q['showposts'];
2471 $q['posts_per_page'] = $q['showposts'];
2473 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
2474 $q['posts_per_page'] = $q['posts_per_archive_page'];
2475 if ( !isset($q['nopaging']) ) {
2476 if ( $q['posts_per_page'] == -1 ) {
2477 $q['nopaging'] = true;
2479 $q['nopaging'] = false;
2483 if ( $this->is_feed ) {
2484 // This overrides posts_per_page.
2485 if ( ! empty( $q['posts_per_rss'] ) ) {
2486 $q['posts_per_page'] = $q['posts_per_rss'];
2488 $q['posts_per_page'] = get_option( 'posts_per_rss' );
2490 $q['nopaging'] = false;
2492 $q['posts_per_page'] = (int) $q['posts_per_page'];
2493 if ( $q['posts_per_page'] < -1 )
2494 $q['posts_per_page'] = abs($q['posts_per_page']);
2495 elseif ( $q['posts_per_page'] == 0 )
2496 $q['posts_per_page'] = 1;
2498 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
2499 $q['comments_per_page'] = get_option('comments_per_page');
2501 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
2502 $this->is_page = true;
2503 $this->is_home = false;
2504 $q['page_id'] = get_option('page_on_front');
2507 if ( isset($q['page']) ) {
2508 $q['page'] = trim($q['page'], '/');
2509 $q['page'] = absint($q['page']);
2512 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
2513 if ( isset($q['no_found_rows']) )
2514 $q['no_found_rows'] = (bool) $q['no_found_rows'];
2516 $q['no_found_rows'] = false;
2518 switch ( $q['fields'] ) {
2520 $fields = "$wpdb->posts.ID";
2523 $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent";
2526 $fields = "$wpdb->posts.*";
2529 if ( '' !== $q['menu_order'] )
2530 $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order'];
2532 // The "m" parameter is meant for months but accepts datetimes of varying specificity
2534 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
2535 if ( strlen($q['m']) > 5 )
2536 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
2537 if ( strlen($q['m']) > 7 )
2538 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
2539 if ( strlen($q['m']) > 9 )
2540 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
2541 if ( strlen($q['m']) > 11 )
2542 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
2543 if ( strlen($q['m']) > 13 )
2544 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
2547 // Handle the other individual date parameters
2548 $date_parameters = array();
2550 if ( '' !== $q['hour'] )
2551 $date_parameters['hour'] = $q['hour'];
2553 if ( '' !== $q['minute'] )
2554 $date_parameters['minute'] = $q['minute'];
2556 if ( '' !== $q['second'] )
2557 $date_parameters['second'] = $q['second'];
2560 $date_parameters['year'] = $q['year'];
2562 if ( $q['monthnum'] )
2563 $date_parameters['monthnum'] = $q['monthnum'];
2566 $date_parameters['week'] = $q['w'];
2569 $date_parameters['day'] = $q['day'];
2571 if ( $date_parameters ) {
2572 $date_query = new WP_Date_Query( array( $date_parameters ) );
2573 $where .= $date_query->get_sql();
2575 unset( $date_parameters, $date_query );
2577 // Handle complex date queries
2578 if ( ! empty( $q['date_query'] ) ) {
2579 $this->date_query = new WP_Date_Query( $q['date_query'] );
2580 $where .= $this->date_query->get_sql();
2584 // If we've got a post_type AND it's not "any" post_type.
2585 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
2586 foreach ( (array)$q['post_type'] as $_post_type ) {
2587 $ptype_obj = get_post_type_object($_post_type);
2588 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
2591 if ( ! $ptype_obj->hierarchical ) {
2592 // Non-hierarchical post types can directly use 'name'.
2593 $q['name'] = $q[ $ptype_obj->query_var ];
2595 // Hierarchical post types will operate through 'pagename'.
2596 $q['pagename'] = $q[ $ptype_obj->query_var ];
2600 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
2606 if ( '' != $q['name'] ) {
2607 $q['name'] = sanitize_title_for_query( $q['name'] );
2608 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
2609 } elseif ( '' != $q['pagename'] ) {
2610 if ( isset($this->queried_object_id) ) {
2611 $reqpage = $this->queried_object_id;
2613 if ( 'page' != $q['post_type'] ) {
2614 foreach ( (array)$q['post_type'] as $_post_type ) {
2615 $ptype_obj = get_post_type_object($_post_type);
2616 if ( !$ptype_obj || !$ptype_obj->hierarchical )
2619 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
2625 $reqpage = get_page_by_path($q['pagename']);
2627 if ( !empty($reqpage) )
2628 $reqpage = $reqpage->ID;
2633 $page_for_posts = get_option('page_for_posts');
2634 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
2635 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
2636 $q['name'] = $q['pagename'];
2637 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
2638 $reqpage_obj = get_post( $reqpage );
2639 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
2640 $this->is_attachment = true;
2641 $post_type = $q['post_type'] = 'attachment';
2642 $this->is_page = true;
2643 $q['attachment_id'] = $reqpage;
2646 } elseif ( '' != $q['attachment'] ) {
2647 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
2648 $q['name'] = $q['attachment'];
2649 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
2653 if ( intval($q['comments_popup']) )
2654 $q['p'] = absint($q['comments_popup']);
2656 // If an attachment is requested by number, let it supersede any post number.
2657 if ( $q['attachment_id'] )
2658 $q['p'] = absint($q['attachment_id']);
2660 // If a post number is specified, load that post
2662 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
2663 } elseif ( $q['post__in'] ) {
2664 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
2665 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
2666 } elseif ( $q['post__not_in'] ) {
2667 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
2668 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
2671 if ( is_numeric( $q['post_parent'] ) ) {
2672 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
2673 } elseif ( $q['post_parent__in'] ) {
2674 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
2675 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
2676 } elseif ( $q['post_parent__not_in'] ) {
2677 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
2678 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
2681 if ( $q['page_id'] ) {
2682 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
2683 $q['p'] = $q['page_id'];
2684 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
2688 // If a search pattern is specified, load the posts that match.
2689 if ( ! empty( $q['s'] ) ) {
2690 $search = $this->parse_search( $q );
2694 * Filter the search SQL that is used in the WHERE clause of WP_Query.
2698 * @param string $search Search SQL for WHERE clause.
2699 * @param WP_Query $this The current WP_Query object.
2701 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
2704 if ( !$this->is_singular ) {
2705 $this->parse_tax_query( $q );
2707 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2709 $join .= $clauses['join'];
2710 $where .= $clauses['where'];
2713 if ( $this->is_tax ) {
2714 if ( empty($post_type) ) {
2715 // Do a fully inclusive search for currently registered post types of queried taxonomies
2716 $post_type = array();
2717 $taxonomies = array_keys( $this->tax_query->queried_terms );
2718 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2719 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2720 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2725 elseif ( count( $post_type ) == 1 )
2726 $post_type = $post_type[0];
2728 $post_status_join = true;
2729 } elseif ( in_array('attachment', (array) $post_type) ) {
2730 $post_status_join = true;
2735 * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2736 * 'category_name' vars are set for backward compatibility.
2738 if ( ! empty( $this->tax_query->queried_terms ) ) {
2741 * Set 'taxonomy', 'term', and 'term_id' to the
2742 * first taxonomy other than 'post_tag' or 'category'.
2744 if ( ! isset( $q['taxonomy'] ) ) {
2745 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2746 if ( empty( $queried_items['terms'][0] ) ) {
2750 if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2751 $q['taxonomy'] = $queried_taxonomy;
2753 if ( 'slug' === $queried_items['field'] ) {
2754 $q['term'] = $queried_items['terms'][0];
2756 $q['term_id'] = $queried_items['terms'][0];
2762 // 'cat', 'category_name', 'tag_id'
2763 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2764 if ( empty( $queried_items['terms'][0] ) ) {
2768 if ( 'category' === $queried_taxonomy ) {
2769 $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2771 $this->set( 'cat', $the_cat->term_id );
2772 $this->set( 'category_name', $the_cat->slug );
2777 if ( 'post_tag' === $queried_taxonomy ) {
2778 $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2780 $this->set( 'tag_id', $the_tag->term_id );
2787 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2788 $groupby = "{$wpdb->posts}.ID";
2791 // Author/user stuff
2793 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2794 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2795 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2796 foreach ( $authors as $author ) {
2797 $key = $author > 0 ? 'author__in' : 'author__not_in';
2798 $q[$key][] = abs( $author );
2800 $q['author'] = implode( ',', $authors );
2803 if ( ! empty( $q['author__not_in'] ) ) {
2804 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2805 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2806 } elseif ( ! empty( $q['author__in'] ) ) {
2807 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2808 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2811 // Author stuff for nice URLs
2813 if ( '' != $q['author_name'] ) {
2814 if ( strpos($q['author_name'], '/') !== false ) {
2815 $q['author_name'] = explode('/', $q['author_name']);
2816 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2817 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2819 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2822 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2823 $q['author'] = get_user_by('slug', $q['author_name']);
2825 $q['author'] = $q['author']->ID;
2826 $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')';
2829 // MIME-Type stuff for attachment browsing
2831 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] )
2832 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2834 $where .= $search . $whichauthor . $whichmimetype;
2836 if ( ! empty( $this->meta_query->queries ) ) {
2837 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
2838 $join .= $clauses['join'];
2839 $where .= $clauses['where'];
2842 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2843 if ( ! isset( $q['order'] ) ) {
2844 $q['order'] = $rand ? '' : 'DESC';
2846 $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2850 if ( empty( $q['orderby'] ) ) {
2852 * Boolean false or empty array blanks out ORDER BY,
2853 * while leaving the value unset or otherwise empty sets the default.
2855 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2858 $orderby = "$wpdb->posts.post_date " . $q['order'];
2860 } elseif ( 'none' == $q['orderby'] ) {
2862 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2863 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2864 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2865 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2867 $orderby_array = array();
2868 if ( is_array( $q['orderby'] ) ) {
2869 foreach ( $q['orderby'] as $_orderby => $order ) {
2870 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2871 $parsed = $this->parse_orderby( $orderby );
2877 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2879 $orderby = implode( ', ', $orderby_array );
2882 $q['orderby'] = urldecode( $q['orderby'] );
2883 $q['orderby'] = addslashes_gpc( $q['orderby'] );
2885 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
2886 $parsed = $this->parse_orderby( $orderby );
2887 // Only allow certain values for safety.
2892 $orderby_array[] = $parsed;
2894 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
2896 if ( empty( $orderby ) ) {
2897 $orderby = "$wpdb->posts.post_date " . $q['order'];
2898 } elseif ( ! empty( $q['order'] ) ) {
2899 $orderby .= " {$q['order']}";
2904 // Order search results by relevance only when another "orderby" is not specified in the query.
2905 if ( ! empty( $q['s'] ) ) {
2906 $search_orderby = '';
2907 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
2908 $search_orderby = $this->parse_search_order( $q );
2911 * Filter the ORDER BY used when ordering search results.
2915 * @param string $search_orderby The ORDER BY clause.
2916 * @param WP_Query $this The current WP_Query instance.
2918 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
2919 if ( $search_orderby )
2920 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
2923 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
2924 $post_type_cap = 'multiple_post_type';
2926 if ( is_array( $post_type ) )
2927 $post_type = reset( $post_type );
2928 $post_type_object = get_post_type_object( $post_type );
2929 if ( empty( $post_type_object ) )
2930 $post_type_cap = $post_type;
2933 if ( isset( $q['post_password'] ) ) {
2934 $where .= $wpdb->prepare( " AND $wpdb->posts.post_password = %s", $q['post_password'] );
2935 if ( empty( $q['perm'] ) ) {
2936 $q['perm'] = 'readable';
2938 } elseif ( isset( $q['has_password'] ) ) {
2939 $where .= sprintf( " AND $wpdb->posts.post_password %s ''", $q['has_password'] ? '!=' : '=' );
2942 if ( 'any' == $post_type ) {
2943 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
2944 if ( empty( $in_search_post_types ) )
2945 $where .= ' AND 1=0 ';
2947 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')";
2948 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
2949 $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')";
2950 } elseif ( ! empty( $post_type ) ) {
2951 $where .= " AND $wpdb->posts.post_type = '$post_type'";
2952 $post_type_object = get_post_type_object ( $post_type );
2953 } elseif ( $this->is_attachment ) {
2954 $where .= " AND $wpdb->posts.post_type = 'attachment'";
2955 $post_type_object = get_post_type_object ( 'attachment' );
2956 } elseif ( $this->is_page ) {
2957 $where .= " AND $wpdb->posts.post_type = 'page'";
2958 $post_type_object = get_post_type_object ( 'page' );
2960 $where .= " AND $wpdb->posts.post_type = 'post'";
2961 $post_type_object = get_post_type_object ( 'post' );
2964 $edit_cap = 'edit_post';
2965 $read_cap = 'read_post';
2967 if ( ! empty( $post_type_object ) ) {
2968 $edit_others_cap = $post_type_object->cap->edit_others_posts;
2969 $read_private_cap = $post_type_object->cap->read_private_posts;
2971 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
2972 $read_private_cap = 'read_private_' . $post_type_cap . 's';
2975 $user_id = get_current_user_id();
2977 $q_status = array();
2978 if ( ! empty( $q['post_status'] ) ) {
2979 $statuswheres = array();
2980 $q_status = $q['post_status'];
2981 if ( ! is_array( $q_status ) )
2982 $q_status = explode(',', $q_status);
2983 $r_status = array();
2984 $p_status = array();
2985 $e_status = array();
2986 if ( in_array( 'any', $q_status ) ) {
2987 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
2988 if ( ! in_array( $status, $q_status ) ) {
2989 $e_status[] = "$wpdb->posts.post_status <> '$status'";
2993 foreach ( get_post_stati() as $status ) {
2994 if ( in_array( $status, $q_status ) ) {
2995 if ( 'private' == $status )
2996 $p_status[] = "$wpdb->posts.post_status = '$status'";
2998 $r_status[] = "$wpdb->posts.post_status = '$status'";
3003 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
3004 $r_status = array_merge($r_status, $p_status);
3008 if ( !empty($e_status) ) {
3009 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
3011 if ( !empty($r_status) ) {
3012 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) )
3013 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
3015 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
3017 if ( !empty($p_status) ) {
3018 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) )
3019 $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
3021 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
3023 if ( $post_status_join ) {
3024 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
3025 foreach ( $statuswheres as $index => $statuswhere )
3026 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
3028 $where_status = implode( ' OR ', $statuswheres );
3029 if ( ! empty( $where_status ) ) {
3030 $where .= " AND ($where_status)";
3032 } elseif ( !$this->is_singular ) {
3033 $where .= " AND ($wpdb->posts.post_status = 'publish'";
3035 // Add public states.
3036 $public_states = get_post_stati( array('public' => true) );
3037 foreach ( (array) $public_states as $state ) {
3038 if ( 'publish' == $state ) // Publish is hard-coded above.
3040 $where .= " OR $wpdb->posts.post_status = '$state'";
3043 if ( $this->is_admin ) {
3044 // Add protected states that should show in the admin all list.
3045 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
3046 foreach ( (array) $admin_all_states as $state )
3047 $where .= " OR $wpdb->posts.post_status = '$state'";
3050 if ( is_user_logged_in() ) {
3051 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
3052 $private_states = get_post_stati( array('private' => true) );
3053 foreach ( (array) $private_states as $state )
3054 $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'";
3061 * Apply filters on where and join prior to paging so that any
3062 * manipulations to them are reflected in the paging by day queries.
3064 if ( !$q['suppress_filters'] ) {
3066 * Filter the WHERE clause of the query.
3070 * @param string $where The WHERE clause of the query.
3071 * @param WP_Query &$this The WP_Query instance (passed by reference).
3073 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
3076 * Filter the JOIN clause of the query.
3080 * @param string $where The JOIN clause of the query.
3081 * @param WP_Query &$this The WP_Query instance (passed by reference).
3083 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
3087 if ( empty($q['nopaging']) && !$this->is_singular ) {
3088 $page = absint($q['paged']);
3092 if ( empty($q['offset']) ) {
3093 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
3094 } else { // we're ignoring $page and using 'offset'
3095 $q['offset'] = absint($q['offset']);
3096 $pgstrt = $q['offset'] . ', ';
3098 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
3102 if ( $this->is_comment_feed && ! $this->is_singular ) {
3103 if ( $this->is_archive || $this->is_search ) {
3104 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
3105 $cwhere = "WHERE comment_approved = '1' $where";
3106 $cgroupby = "$wpdb->comments.comment_id";
3107 } else { // Other non singular e.g. front
3108 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
3109 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
3113 if ( !$q['suppress_filters'] ) {
3115 * Filter the JOIN clause of the comments feed query before sending.
3119 * @param string $cjoin The JOIN clause of the query.
3120 * @param WP_Query &$this The WP_Query instance (passed by reference).
3122 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
3125 * Filter the WHERE clause of the comments feed query before sending.
3129 * @param string $cwhere The WHERE clause of the query.
3130 * @param WP_Query &$this The WP_Query instance (passed by reference).
3132 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
3135 * Filter the GROUP BY clause of the comments feed query before sending.
3139 * @param string $cgroupby The GROUP BY clause of the query.
3140 * @param WP_Query &$this The WP_Query instance (passed by reference).
3142 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
3145 * Filter the ORDER BY clause of the comments feed query before sending.
3149 * @param string $corderby The ORDER BY clause of the query.
3150 * @param WP_Query &$this The WP_Query instance (passed by reference).
3152 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3155 * Filter the LIMIT clause of the comments feed query before sending.
3159 * @param string $climits The JOIN clause of the query.
3160 * @param WP_Query &$this The WP_Query instance (passed by reference).
3162 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3164 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3165 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3167 $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
3168 $this->comment_count = count($this->comments);
3170 $post_ids = array();
3172 foreach ( $this->comments as $comment )
3173 $post_ids[] = (int) $comment->comment_post_ID;
3175 $post_ids = join(',', $post_ids);
3178 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
3183 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
3186 * Apply post-paging filters on where and join. Only plugins that
3187 * manipulate paging queries should use these hooks.
3189 if ( !$q['suppress_filters'] ) {
3191 * Filter the WHERE clause of the query.
3193 * Specifically for manipulating paging queries.
3197 * @param string $where The WHERE clause of the query.
3198 * @param WP_Query &$this The WP_Query instance (passed by reference).
3200 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
3203 * Filter the GROUP BY clause of the query.
3207 * @param string $groupby The GROUP BY clause of the query.
3208 * @param WP_Query &$this The WP_Query instance (passed by reference).
3210 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
3213 * Filter the JOIN clause of the query.
3215 * Specifically for manipulating paging queries.
3219 * @param string $join The JOIN clause of the query.
3220 * @param WP_Query &$this The WP_Query instance (passed by reference).
3222 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
3225 * Filter the ORDER BY clause of the query.
3229 * @param string $orderby The ORDER BY clause of the query.
3230 * @param WP_Query &$this The WP_Query instance (passed by reference).
3232 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
3235 * Filter the DISTINCT clause of the query.
3239 * @param string $distinct The DISTINCT clause of the query.
3240 * @param WP_Query &$this The WP_Query instance (passed by reference).
3242 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
3245 * Filter the LIMIT clause of the query.
3249 * @param string $limits The LIMIT clause of the query.
3250 * @param WP_Query &$this The WP_Query instance (passed by reference).
3252 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
3255 * Filter the SELECT clause of the query.
3259 * @param string $fields The SELECT clause of the query.
3260 * @param WP_Query &$this The WP_Query instance (passed by reference).
3262 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
3265 * Filter all query clauses at once, for convenience.
3267 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3268 * fields (SELECT), and LIMITS clauses.
3272 * @param array $clauses The list of clauses for the query.
3273 * @param WP_Query &$this The WP_Query instance (passed by reference).
3275 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
3277 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3278 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3279 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3280 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3281 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3282 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3283 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3287 * Fires to announce the query's current selection parameters.
3289 * For use by caching plugins.
3293 * @param string $selection The assembled selection query.
3295 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
3298 * Filter again for the benefit of caching plugins.
3299 * Regular plugins should use the hooks above.
3301 if ( !$q['suppress_filters'] ) {
3303 * Filter the WHERE clause of the query.
3305 * For use by caching plugins.
3309 * @param string $where The WHERE clause of the query.
3310 * @param WP_Query &$this The WP_Query instance (passed by reference).
3312 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
3315 * Filter the GROUP BY clause of the query.
3317 * For use by caching plugins.
3321 * @param string $groupby The GROUP BY clause of the query.
3322 * @param WP_Query &$this The WP_Query instance (passed by reference).
3324 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
3327 * Filter the JOIN clause of the query.
3329 * For use by caching plugins.
3333 * @param string $join The JOIN clause of the query.
3334 * @param WP_Query &$this The WP_Query instance (passed by reference).
3336 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
3339 * Filter the ORDER BY clause of the query.
3341 * For use by caching plugins.
3345 * @param string $orderby The ORDER BY clause of the query.
3346 * @param WP_Query &$this The WP_Query instance (passed by reference).
3348 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
3351 * Filter the DISTINCT clause of the query.
3353 * For use by caching plugins.
3357 * @param string $distinct The DISTINCT clause of the query.
3358 * @param WP_Query &$this The WP_Query instance (passed by reference).
3360 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
3363 * Filter the SELECT clause of the query.
3365 * For use by caching plugins.
3369 * @param string $fields The SELECT clause of the query.
3370 * @param WP_Query &$this The WP_Query instance (passed by reference).
3372 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
3375 * Filter the LIMIT clause of the query.
3377 * For use by caching plugins.
3381 * @param string $limits The LIMIT clause of the query.
3382 * @param WP_Query &$this The WP_Query instance (passed by reference).
3384 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
3387 * Filter all query clauses at once, for convenience.
3389 * For use by caching plugins.
3391 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
3392 * fields (SELECT), and LIMITS clauses.
3396 * @param array $pieces The pieces of the query.
3397 * @param WP_Query &$this The WP_Query instance (passed by reference).
3399 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
3401 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
3402 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
3403 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
3404 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
3405 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
3406 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
3407 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
3410 if ( ! empty($groupby) )
3411 $groupby = 'GROUP BY ' . $groupby;
3412 if ( !empty( $orderby ) )
3413 $orderby = 'ORDER BY ' . $orderby;
3416 if ( !$q['no_found_rows'] && !empty($limits) )
3417 $found_rows = 'SQL_CALC_FOUND_ROWS';
3419 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3421 if ( !$q['suppress_filters'] ) {
3423 * Filter the completed SQL query before sending.
3427 * @param array $request The complete SQL query.
3428 * @param WP_Query &$this The WP_Query instance (passed by reference).
3430 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
3433 if ( 'ids' == $q['fields'] ) {
3434 $this->posts = $wpdb->get_col( $this->request );
3435 $this->posts = array_map( 'intval', $this->posts );
3436 $this->post_count = count( $this->posts );
3437 $this->set_found_posts( $q, $limits );
3439 return $this->posts;
3442 if ( 'id=>parent' == $q['fields'] ) {
3443 $this->posts = $wpdb->get_results( $this->request );
3444 $this->post_count = count( $this->posts );
3445 $this->set_found_posts( $q, $limits );
3448 foreach ( $this->posts as $key => $post ) {
3449 $this->posts[ $key ]->ID = (int) $post->ID;
3450 $this->posts[ $key ]->post_parent = (int) $post->post_parent;
3452 $r[ (int) $post->ID ] = (int) $post->post_parent;
3458 $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
3461 * Filter whether to split the query.
3463 * Splitting the query will cause it to fetch just the IDs of the found posts
3464 * (and then individually fetch each post by ID), rather than fetching every
3465 * complete row at once. One massive result vs. many small results.
3469 * @param bool $split_the_query Whether or not to split the query.
3470 * @param WP_Query $this The WP_Query instance.
3472 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
3474 if ( $split_the_query ) {
3475 // First get the IDs and then fill in the objects
3477 $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
3480 * Filter the Post IDs SQL request before sending.
3484 * @param string $request The post ID request.
3485 * @param WP_Query $this The WP_Query instance.
3487 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
3489 $ids = $wpdb->get_col( $this->request );
3492 $this->posts = $ids;
3493 $this->set_found_posts( $q, $limits );
3494 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
3496 $this->posts = array();
3499 $this->posts = $wpdb->get_results( $this->request );
3500 $this->set_found_posts( $q, $limits );
3503 // Convert to WP_Post objects
3505 $this->posts = array_map( 'get_post', $this->posts );
3507 if ( ! $q['suppress_filters'] ) {
3509 * Filter the raw post results array, prior to status checks.
3513 * @param array $posts The post results array.
3514 * @param WP_Query &$this The WP_Query instance (passed by reference).
3516 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
3519 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
3520 /** This filter is documented in wp-includes/query.php */
3521 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
3523 /** This filter is documented in wp-includes/query.php */
3524 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
3526 /** This filter is documented in wp-includes/query.php */
3527 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
3528 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
3530 /** This filter is documented in wp-includes/query.php */
3531 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
3532 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
3534 /** This filter is documented in wp-includes/query.php */
3535 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
3537 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
3538 $this->comments = $wpdb->get_results($comments_request);
3539 $this->comment_count = count($this->comments);
3542 // Check post status to determine if post should be displayed.
3543 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
3544 $status = get_post_status($this->posts[0]);
3545 $post_status_obj = get_post_status_object($status);
3546 //$type = get_post_type($this->posts[0]);
3548 // If the post_status was specifically requested, let it pass through.
3549 if ( !$post_status_obj->public && ! in_array( $status, $q_status ) ) {
3551 if ( ! is_user_logged_in() ) {
3552 // User must be logged in to view unpublished posts.
3553 $this->posts = array();
3555 if ( $post_status_obj->protected ) {
3556 // User must have edit permissions on the draft to preview.
3557 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
3558 $this->posts = array();
3560 $this->is_preview = true;
3561 if ( 'future' != $status )
3562 $this->posts[0]->post_date = current_time('mysql');
3564 } elseif ( $post_status_obj->private ) {
3565 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
3566 $this->posts = array();
3568 $this->posts = array();
3573 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
3575 * Filter the single post for preview mode.
3579 * @param WP_Post $post_preview The Post object.
3580 * @param WP_Query &$this The WP_Query instance (passed by reference).
3582 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
3586 // Put sticky posts at the top of the posts array
3587 $sticky_posts = get_option('sticky_posts');
3588 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
3589 $num_posts = count($this->posts);
3591 // Loop over posts and relocate stickies to the front.
3592 for ( $i = 0; $i < $num_posts; $i++ ) {
3593 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
3594 $sticky_post = $this->posts[$i];
3595 // Remove sticky from current position
3596 array_splice($this->posts, $i, 1);
3597 // Move to front, after other stickies
3598 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
3599 // Increment the sticky offset. The next sticky will be placed at this offset.
3601 // Remove post from sticky posts array
3602 $offset = array_search($sticky_post->ID, $sticky_posts);
3603 unset( $sticky_posts[$offset] );
3607 // If any posts have been excluded specifically, Ignore those that are sticky.
3608 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
3609 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
3611 // Fetch sticky posts that weren't in the query results
3612 if ( !empty($sticky_posts) ) {
3613 $stickies = get_posts( array(
3614 'post__in' => $sticky_posts,
3615 'post_type' => $post_type,
3616 'post_status' => 'publish',
3620 foreach ( $stickies as $sticky_post ) {
3621 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
3627 if ( ! $q['suppress_filters'] ) {
3629 * Filter the array of retrieved posts after they've been fetched and
3630 * internally processed.
3634 * @param array $posts The array of retrieved posts.
3635 * @param WP_Query &$this The WP_Query instance (passed by reference).
3637 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3640 // Ensure that any posts added/modified via one of the filters above are
3641 // of the type WP_Post and are filtered.
3642 if ( $this->posts ) {
3643 $this->post_count = count( $this->posts );
3645 $this->posts = array_map( 'get_post', $this->posts );
3647 if ( $q['cache_results'] )
3648 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3650 $this->post = reset( $this->posts );
3652 $this->post_count = 0;
3653 $this->posts = array();
3656 return $this->posts;
3660 * Set up the amount of found posts and the number of pages (if limit clause was used)
3661 * for the current query.
3666 * @global wpdb $wpdb
3668 private function set_found_posts( $q, $limits ) {
3671 // Bail if posts is an empty array. Continue if posts is an empty string,
3672 // null, or false to accommodate caching plugins that fill posts later.
3673 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3676 if ( ! empty( $limits ) ) {
3678 * Filter the query to run for retrieving the found posts.
3682 * @param string $found_posts The query to run to find the found posts.
3683 * @param WP_Query &$this The WP_Query instance (passed by reference).
3685 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3687 $this->found_posts = count( $this->posts );
3691 * Filter the number of found posts for the query.
3695 * @param int $found_posts The number of posts found.
3696 * @param WP_Query &$this The WP_Query instance (passed by reference).
3698 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3700 if ( ! empty( $limits ) )
3701 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3705 * Set up the next post and iterate current post index.
3710 * @return WP_Post Next post.
3712 public function next_post() {
3714 $this->current_post++;
3716 $this->post = $this->posts[$this->current_post];
3721 * Sets up the current post.
3723 * Retrieves the next post, sets up the post, sets the 'in the loop'
3729 * @global WP_Post $post
3731 public function the_post() {
3733 $this->in_the_loop = true;
3735 if ( $this->current_post == -1 ) // loop has just started
3737 * Fires once the loop is started.
3741 * @param WP_Query &$this The WP_Query instance (passed by reference).
3743 do_action_ref_array( 'loop_start', array( &$this ) );
3745 $post = $this->next_post();
3746 $this->setup_postdata( $post );
3750 * Whether there are more posts available in the loop.
3752 * Calls action 'loop_end', when the loop is complete.
3757 * @return bool True if posts are available, false if end of loop.
3759 public function have_posts() {
3760 if ( $this->current_post + 1 < $this->post_count ) {
3762 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3764 * Fires once the loop has ended.
3768 * @param WP_Query &$this The WP_Query instance (passed by reference).
3770 do_action_ref_array( 'loop_end', array( &$this ) );
3771 // Do some cleaning up after the loop
3772 $this->rewind_posts();
3775 $this->in_the_loop = false;
3780 * Rewind the posts and reset post index.
3785 public function rewind_posts() {
3786 $this->current_post = -1;
3787 if ( $this->post_count > 0 ) {
3788 $this->post = $this->posts[0];
3793 * Iterate current comment index and return comment object.
3798 * @return object Comment object.
3800 public function next_comment() {
3801 $this->current_comment++;
3803 $this->comment = $this->comments[$this->current_comment];
3804 return $this->comment;
3808 * Sets up the current comment.
3812 * @global object $comment Current comment.
3814 public function the_comment() {
3817 $comment = $this->next_comment();
3819 if ( $this->current_comment == 0 ) {
3821 * Fires once the comment loop is started.
3825 do_action( 'comment_loop_start' );
3830 * Whether there are more comments available.
3832 * Automatically rewinds comments when finished.
3837 * @return bool True, if more comments. False, if no more posts.
3839 public function have_comments() {
3840 if ( $this->current_comment + 1 < $this->comment_count ) {
3842 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
3843 $this->rewind_comments();
3850 * Rewind the comments, resets the comment index and comment to first.
3855 public function rewind_comments() {
3856 $this->current_comment = -1;
3857 if ( $this->comment_count > 0 ) {
3858 $this->comment = $this->comments[0];
3863 * Sets up the WordPress query by parsing query string.
3868 * @param string $query URL query string.
3869 * @return array List of posts.
3871 public function query( $query ) {
3873 $this->query = $this->query_vars = wp_parse_args( $query );
3874 return $this->get_posts();
3878 * Retrieve queried object.
3880 * If queried object is not set, then the queried object will be set from
3881 * the category, tag, taxonomy, posts page, single post, page, or author
3882 * query variable. After it is set up, it will be returned.
3889 public function get_queried_object() {
3890 if ( isset($this->queried_object) )
3891 return $this->queried_object;
3893 $this->queried_object = null;
3894 $this->queried_object_id = 0;
3896 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
3897 if ( $this->is_category ) {
3898 if ( $this->get( 'cat' ) ) {
3899 $term = get_term( $this->get( 'cat' ), 'category' );
3900 } elseif ( $this->get( 'category_name' ) ) {
3901 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
3903 } elseif ( $this->is_tag ) {
3904 if ( $this->get( 'tag_id' ) ) {
3905 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
3906 } elseif ( $this->get( 'tag' ) ) {
3907 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
3910 // For other tax queries, grab the first term from the first clause.
3911 $tax_query_in_and = wp_list_filter( $this->tax_query->queried_terms, array( 'operator' => 'NOT IN' ), 'NOT' );
3913 if ( ! empty( $tax_query_in_and ) ) {
3914 $queried_taxonomies = array_keys( $tax_query_in_and );
3915 $matched_taxonomy = reset( $queried_taxonomies );
3916 $query = $tax_query_in_and[ $matched_taxonomy ];
3918 if ( $query['terms'] ) {
3919 if ( 'term_id' == $query['field'] ) {
3920 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
3922 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
3928 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
3929 $this->queried_object = $term;
3930 $this->queried_object_id = (int) $term->term_id;
3932 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
3933 _make_cat_compat( $this->queried_object );
3935 } elseif ( $this->is_post_type_archive ) {
3936 $post_type = $this->get( 'post_type' );
3937 if ( is_array( $post_type ) )
3938 $post_type = reset( $post_type );
3939 $this->queried_object = get_post_type_object( $post_type );
3940 } elseif ( $this->is_posts_page ) {
3941 $page_for_posts = get_option('page_for_posts');
3942 $this->queried_object = get_post( $page_for_posts );
3943 $this->queried_object_id = (int) $this->queried_object->ID;
3944 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
3945 $this->queried_object = $this->post;
3946 $this->queried_object_id = (int) $this->post->ID;
3947 } elseif ( $this->is_author ) {
3948 $this->queried_object_id = (int) $this->get('author');
3949 $this->queried_object = get_userdata( $this->queried_object_id );
3952 return $this->queried_object;
3956 * Retrieve ID of the current queried object.
3963 public function get_queried_object_id() {
3964 $this->get_queried_object();
3966 if ( isset($this->queried_object_id) ) {
3967 return $this->queried_object_id;
3976 * Sets up the WordPress query, if parameter is not empty.
3981 * @param string|array $query URL query string or array of vars.
3983 public function __construct($query = '') {
3984 if ( ! empty($query) ) {
3985 $this->query($query);
3990 * Make private properties readable for backwards compatibility.
3995 * @param string $name Property to get.
3996 * @return mixed Property.
3998 public function __get( $name ) {
3999 if ( in_array( $name, $this->compat_fields ) ) {
4000 return $this->$name;
4005 * Make private properties checkable for backwards compatibility.
4010 * @param string $name Property to check if set.
4011 * @return bool Whether the property is set.
4013 public function __isset( $name ) {
4014 if ( in_array( $name, $this->compat_fields ) ) {
4015 return isset( $this->$name );
4020 * Make private/protected methods readable for backwards compatibility.
4025 * @param callable $name Method to call.
4026 * @param array $arguments Arguments to pass when calling.
4027 * @return mixed|false Return value of the callback, false otherwise.
4029 public function __call( $name, $arguments ) {
4030 if ( in_array( $name, $this->compat_methods ) ) {
4031 return call_user_func_array( array( $this, $name ), $arguments );
4037 * Is the query for an existing archive page?
4039 * Month, Year, Category, Author, Post Type archive...
4045 public function is_archive() {
4046 return (bool) $this->is_archive;
4050 * Is the query for an existing post type archive page?
4054 * @param mixed $post_types Optional. Post type or array of posts types to check against.
4057 public function is_post_type_archive( $post_types = '' ) {
4058 if ( empty( $post_types ) || ! $this->is_post_type_archive )
4059 return (bool) $this->is_post_type_archive;
4061 $post_type = $this->get( 'post_type' );
4062 if ( is_array( $post_type ) )
4063 $post_type = reset( $post_type );
4064 $post_type_object = get_post_type_object( $post_type );
4066 return in_array( $post_type_object->name, (array) $post_types );
4070 * Is the query for an existing attachment page?
4074 * @param mixed $attachment Attachment ID, title, slug, or array of such.
4077 public function is_attachment( $attachment = '' ) {
4078 if ( ! $this->is_attachment ) {
4082 if ( empty( $attachment ) ) {
4086 $attachment = (array) $attachment;
4088 $post_obj = $this->get_queried_object();
4090 if ( in_array( (string) $post_obj->ID, $attachment ) ) {
4092 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
4094 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
4101 * Is the query for an existing author archive page?
4103 * If the $author parameter is specified, this function will additionally
4104 * check if the query is for one of the authors specified.
4108 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
4111 public function is_author( $author = '' ) {
4112 if ( !$this->is_author )
4115 if ( empty($author) )
4118 $author_obj = $this->get_queried_object();
4120 $author = (array) $author;
4122 if ( in_array( (string) $author_obj->ID, $author ) )
4124 elseif ( in_array( $author_obj->nickname, $author ) )
4126 elseif ( in_array( $author_obj->user_nicename, $author ) )
4133 * Is the query for an existing category archive page?
4135 * If the $category parameter is specified, this function will additionally
4136 * check if the query is for one of the categories specified.
4140 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
4143 public function is_category( $category = '' ) {
4144 if ( !$this->is_category )
4147 if ( empty($category) )
4150 $cat_obj = $this->get_queried_object();
4152 $category = (array) $category;
4154 if ( in_array( (string) $cat_obj->term_id, $category ) )
4156 elseif ( in_array( $cat_obj->name, $category ) )
4158 elseif ( in_array( $cat_obj->slug, $category ) )
4165 * Is the query for an existing tag archive page?
4167 * If the $tag parameter is specified, this function will additionally
4168 * check if the query is for one of the tags specified.
4172 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
4175 public function is_tag( $tag = '' ) {
4176 if ( ! $this->is_tag )
4179 if ( empty( $tag ) )
4182 $tag_obj = $this->get_queried_object();
4184 $tag = (array) $tag;
4186 if ( in_array( (string) $tag_obj->term_id, $tag ) )
4188 elseif ( in_array( $tag_obj->name, $tag ) )
4190 elseif ( in_array( $tag_obj->slug, $tag ) )
4197 * Is the query for an existing taxonomy archive page?
4199 * If the $taxonomy parameter is specified, this function will additionally
4200 * check if the query is for that specific $taxonomy.
4202 * If the $term parameter is specified in addition to the $taxonomy parameter,
4203 * this function will additionally check if the query is for one of the terms
4208 * @global array $wp_taxonomies
4210 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
4211 * @param mixed $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
4214 public function is_tax( $taxonomy = '', $term = '' ) {
4215 global $wp_taxonomies;
4217 if ( !$this->is_tax )
4220 if ( empty( $taxonomy ) )
4223 $queried_object = $this->get_queried_object();
4224 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
4225 $term_array = (array) $term;
4227 // Check that the taxonomy matches.
4228 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
4231 // Only a Taxonomy provided.
4232 if ( empty( $term ) )
4235 return isset( $queried_object->term_id ) &&
4236 count( array_intersect(
4237 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
4243 * Whether the current URL is within the comments popup window.
4249 public function is_comments_popup() {
4250 return (bool) $this->is_comments_popup;
4254 * Is the query for an existing date archive?
4260 public function is_date() {
4261 return (bool) $this->is_date;
4265 * Is the query for an existing day archive?
4271 public function is_day() {
4272 return (bool) $this->is_day;
4276 * Is the query for a feed?
4280 * @param string|array $feeds Optional feed types to check.
4283 public function is_feed( $feeds = '' ) {
4284 if ( empty( $feeds ) || ! $this->is_feed )
4285 return (bool) $this->is_feed;
4286 $qv = $this->get( 'feed' );
4287 if ( 'feed' == $qv )
4288 $qv = get_default_feed();
4289 return in_array( $qv, (array) $feeds );
4293 * Is the query for a comments feed?
4299 public function is_comment_feed() {
4300 return (bool) $this->is_comment_feed;
4304 * Is the query for the front page of the site?
4306 * This is for what is displayed at your site's main URL.
4308 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
4310 * If you set a static page for the front page of your site, this function will return
4311 * true when viewing that page.
4313 * Otherwise the same as @see WP_Query::is_home()
4317 * @return bool True, if front of site.
4319 public function is_front_page() {
4321 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
4323 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
4330 * Is the query for the blog homepage?
4332 * This is the page which shows the time based blog content of your site.
4334 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
4336 * If you set a static page for the front page of your site, this function will return
4337 * true only on the page you set as the "Posts page".
4339 * @see WP_Query::is_front_page()
4343 * @return bool True if blog view homepage.
4345 public function is_home() {
4346 return (bool) $this->is_home;
4350 * Is the query for an existing month archive?
4356 public function is_month() {
4357 return (bool) $this->is_month;
4361 * Is the query for an existing single page?
4363 * If the $page parameter is specified, this function will additionally
4364 * check if the query is for one of the pages specified.
4366 * @see WP_Query::is_single()
4367 * @see WP_Query::is_singular()
4371 * @param mixed $page Page ID, title, slug, path, or array of such.
4374 public function is_page( $page = '' ) {
4375 if ( !$this->is_page )
4378 if ( empty( $page ) )
4381 $page_obj = $this->get_queried_object();
4383 $page = (array) $page;
4385 if ( in_array( (string) $page_obj->ID, $page ) ) {
4387 } elseif ( in_array( $page_obj->post_title, $page ) ) {
4389 } elseif ( in_array( $page_obj->post_name, $page ) ) {
4392 foreach ( $page as $pagepath ) {
4393 if ( ! strpos( $pagepath, '/' ) ) {
4396 $pagepath_obj = get_page_by_path( $pagepath );
4398 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
4408 * Is the query for paged result and not for the first page?
4414 public function is_paged() {
4415 return (bool) $this->is_paged;
4419 * Is the query for a post or page preview?
4425 public function is_preview() {
4426 return (bool) $this->is_preview;
4430 * Is the query for the robots file?
4436 public function is_robots() {
4437 return (bool) $this->is_robots;
4441 * Is the query for a search?
4447 public function is_search() {
4448 return (bool) $this->is_search;
4452 * Is the query for an existing single post?
4454 * Works for any post type, except attachments and pages
4456 * If the $post parameter is specified, this function will additionally
4457 * check if the query is for one of the Posts specified.
4459 * @see WP_Query::is_page()
4460 * @see WP_Query::is_singular()
4464 * @param mixed $post Post ID, title, slug, path, or array of such.
4467 public function is_single( $post = '' ) {
4468 if ( !$this->is_single )
4474 $post_obj = $this->get_queried_object();
4476 $post = (array) $post;
4478 if ( in_array( (string) $post_obj->ID, $post ) ) {
4480 } elseif ( in_array( $post_obj->post_title, $post ) ) {
4482 } elseif ( in_array( $post_obj->post_name, $post ) ) {
4485 foreach ( $post as $postpath ) {
4486 if ( ! strpos( $postpath, '/' ) ) {
4489 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
4491 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
4500 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
4502 * If the $post_types parameter is specified, this function will additionally
4503 * check if the query is for one of the Posts Types specified.
4505 * @see WP_Query::is_page()
4506 * @see WP_Query::is_single()
4510 * @param mixed $post_types Optional. Post Type or array of Post Types
4513 public function is_singular( $post_types = '' ) {
4514 if ( empty( $post_types ) || !$this->is_singular )
4515 return (bool) $this->is_singular;
4517 $post_obj = $this->get_queried_object();
4519 return in_array( $post_obj->post_type, (array) $post_types );
4523 * Is the query for a specific time?
4529 public function is_time() {
4530 return (bool) $this->is_time;
4534 * Is the query for a trackback endpoint call?
4540 public function is_trackback() {
4541 return (bool) $this->is_trackback;
4545 * Is the query for an existing year archive?
4551 public function is_year() {
4552 return (bool) $this->is_year;
4556 * Is the query a 404 (returns no results)?
4562 public function is_404() {
4563 return (bool) $this->is_404;
4567 * Is the query the main query?
4571 * @global WP_Query $wp_query
4575 public function is_main_query() {
4576 global $wp_the_query;
4577 return $wp_the_query === $this;
4581 * Set up global post data.
4586 * @global WP_User $authordata
4587 * @global string|int|bool $currentday
4588 * @global string|int|bool $currentmonth
4590 * @global array $pages
4591 * @global int $multipage
4593 * @global int $numpages
4595 * @param WP_Post $post Post data.
4596 * @return true True when finished.
4598 public function setup_postdata( $post ) {
4599 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
4601 $id = (int) $post->ID;
4603 $authordata = get_userdata($post->post_author);
4605 $currentday = mysql2date('d.m.y', $post->post_date, false);
4606 $currentmonth = mysql2date('m', $post->post_date, false);
4609 $page = $this->get( 'page' );
4614 * Force full post content when viewing the permalink for the $post,
4615 * or when on an RSS feed. Otherwise respect the 'more' tag.
4617 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4619 } elseif ( $this->is_feed() ) {
4625 $content = $post->post_content;
4626 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4629 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4630 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4631 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4633 // Ignore nextpage at the beginning of the content.
4634 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4635 $content = substr( $content, 15 );
4637 $pages = explode('<!--nextpage-->', $content);
4638 $numpages = count($pages);
4639 if ( $numpages > 1 )
4642 $pages = array( $post->post_content );
4646 * Fires once the post data has been setup.
4649 * @since 4.1.0 Introduced `$this` parameter.
4651 * @param WP_Post &$post The Post object (passed by reference).
4652 * @param WP_Query &$this The current Query object (passed by reference).
4654 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4659 * After looping through a nested query, this function
4660 * restores the $post global to the current post in this query.
4664 * @global WP_Post $post
4666 public function reset_postdata() {
4667 if ( ! empty( $this->post ) ) {
4668 $GLOBALS['post'] = $this->post;
4669 setup_postdata( $this->post );
4675 * Redirect old slugs to the correct permalink.
4677 * Attempts to find the current slug from the past slugs.
4681 * @global WP_Query $wp_query
4682 * @global wpdb $wpdb WordPress database abstraction object.
4684 function wp_old_slug_redirect() {
4686 if ( is_404() && '' != $wp_query->query_vars['name'] ) :
4689 // Guess the current post_type based on the query vars.
4690 if ( get_query_var('post_type') )
4691 $post_type = get_query_var('post_type');
4692 elseif ( !empty($wp_query->query_vars['pagename']) )
4693 $post_type = 'page';
4695 $post_type = 'post';
4697 if ( is_array( $post_type ) ) {
4698 if ( count( $post_type ) > 1 )
4700 $post_type = reset( $post_type );
4703 // Do not attempt redirect for hierarchical post types
4704 if ( is_post_type_hierarchical( $post_type ) )
4707 $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']);
4709 // if year, monthnum, or day have been specified, make our query more precise
4710 // just in case there are multiple identical _wp_old_slug values
4711 if ( '' != $wp_query->query_vars['year'] )
4712 $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']);
4713 if ( '' != $wp_query->query_vars['monthnum'] )
4714 $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']);
4715 if ( '' != $wp_query->query_vars['day'] )
4716 $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']);
4718 $id = (int) $wpdb->get_var($query);
4723 $link = get_permalink($id);
4728 wp_redirect( $link, 301 ); // Permanent redirect
4734 * Set up global post data.
4738 * @global WP_Query $wp_query
4740 * @param object $post Post data.
4741 * @return bool True when finished.
4743 function setup_postdata( $post ) {
4746 if ( ! empty( $wp_query ) && $wp_query instanceof WP_Query ) {
4747 return $wp_query->setup_postdata( $post );