3 * Query API: WP_Query class
11 * The WordPress Query class.
13 * @link https://codex.wordpress.org/Function_Reference/WP_Query Codex page.
16 * @since 4.5.0 Removed the `$comments_popup` property.
21 * Query vars set by the user
30 * Query vars, after parsing
36 public $query_vars = array();
39 * Taxonomy query, as passed to get_tax_sql()
43 * @var object WP_Tax_Query
48 * Metadata query container
52 * @var object WP_Meta_Query
54 public $meta_query = false;
57 * Date query container
61 * @var object WP_Date_Query
63 public $date_query = false;
66 * Holds the data for a single object that is queried.
68 * Holds the contents of a post, page, category, attachment.
74 public $queried_object;
77 * The ID of the queried object.
83 public $queried_object_id;
86 * Get post database query.
104 * The amount of posts for the current query.
110 public $post_count = 0;
113 * Index of the current item in the loop.
119 public $current_post = -1;
122 * Whether the loop has started and the caller is in the loop.
128 public $in_the_loop = false;
140 * The list of comments for current post.
149 * The amount of comments for the posts.
155 public $comment_count = 0;
158 * The index of the comment in the comment loop.
164 public $current_comment = -1;
167 * Current comment ID.
176 * The amount of found posts for the current query.
178 * If limit clause was not used, equals $post_count.
184 public $found_posts = 0;
187 * The amount of pages.
193 public $max_num_pages = 0;
196 * The amount of comment pages.
202 public $max_num_comment_pages = 0;
205 * Set if query is single post.
211 public $is_single = false;
214 * Set if query is preview of blog.
220 public $is_preview = false;
223 * Set if query returns a page.
229 public $is_page = false;
232 * Set if query is an archive list.
238 public $is_archive = false;
241 * Set if query is part of a date.
247 public $is_date = false;
250 * Set if query contains a year.
256 public $is_year = false;
259 * Set if query contains a month.
265 public $is_month = false;
268 * Set if query contains a day.
274 public $is_day = false;
277 * Set if query contains time.
283 public $is_time = false;
286 * Set if query contains an author.
292 public $is_author = false;
295 * Set if query contains category.
301 public $is_category = false;
304 * Set if query contains tag.
310 public $is_tag = false;
313 * Set if query contains taxonomy.
319 public $is_tax = false;
322 * Set if query was part of a search result.
328 public $is_search = false;
331 * Set if query is feed display.
337 public $is_feed = false;
340 * Set if query is comment feed display.
346 public $is_comment_feed = false;
349 * Set if query is trackback.
355 public $is_trackback = false;
358 * Set if query is blog homepage.
364 public $is_home = false;
367 * Set if query couldn't found anything.
373 public $is_404 = false;
376 * Set if query is embed.
382 public $is_embed = false;
385 * Set if query is paged
391 public $is_paged = false;
394 * Set if query is part of administration page.
400 public $is_admin = false;
403 * Set if query is an attachment.
409 public $is_attachment = false;
412 * Set if is single, is a page, or is an attachment.
418 public $is_singular = false;
421 * Set if query is for robots.
427 public $is_robots = false;
430 * Set if query contains posts.
432 * Basically, the homepage if the option isn't set for the static homepage.
438 public $is_posts_page = false;
441 * Set if query is for a post type archive.
447 public $is_post_type_archive = false;
450 * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know
451 * whether we have to re-parse because something has changed
457 private $query_vars_hash = false;
460 * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made
461 * via pre_get_posts hooks.
466 private $query_vars_changed = true;
469 * Set if post thumbnails are cached
475 public $thumbnails_cached = false;
478 * Cached list of search stopwords.
485 private $compat_fields = array( 'query_vars_hash', 'query_vars_changed' );
487 private $compat_methods = array( 'init_query_flags', 'parse_tax_query' );
490 * Resets query flags to false.
492 * The query flags are what page info WordPress was able to figure out.
497 private function init_query_flags() {
498 $this->is_single = false;
499 $this->is_preview = false;
500 $this->is_page = false;
501 $this->is_archive = false;
502 $this->is_date = false;
503 $this->is_year = false;
504 $this->is_month = false;
505 $this->is_day = false;
506 $this->is_time = false;
507 $this->is_author = false;
508 $this->is_category = false;
509 $this->is_tag = false;
510 $this->is_tax = false;
511 $this->is_search = false;
512 $this->is_feed = false;
513 $this->is_comment_feed = false;
514 $this->is_trackback = false;
515 $this->is_home = false;
516 $this->is_404 = false;
517 $this->is_paged = false;
518 $this->is_admin = false;
519 $this->is_attachment = false;
520 $this->is_singular = false;
521 $this->is_robots = false;
522 $this->is_posts_page = false;
523 $this->is_post_type_archive = false;
527 * Initiates object properties and sets default values.
532 public function init() {
535 $this->query_vars = array();
536 unset($this->queried_object);
537 unset($this->queried_object_id);
538 $this->post_count = 0;
539 $this->current_post = -1;
540 $this->in_the_loop = false;
541 unset( $this->request );
542 unset( $this->post );
543 unset( $this->comments );
544 unset( $this->comment );
545 $this->comment_count = 0;
546 $this->current_comment = -1;
547 $this->found_posts = 0;
548 $this->max_num_pages = 0;
549 $this->max_num_comment_pages = 0;
551 $this->init_query_flags();
555 * Reparse the query vars.
560 public function parse_query_vars() {
561 $this->parse_query();
565 * Fills in the query variables, which do not exist within the parameter.
568 * @since 4.4.0 Removed the `comments_popup` public query variable.
571 * @param array $array Defined query variables.
572 * @return array Complete query variables with undefined ones filled in empty.
574 public function fill_query_vars($array) {
615 foreach ( $keys as $key ) {
616 if ( !isset($array[$key]) )
620 $array_keys = array( 'category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in', 'post_name__in',
621 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'post_parent__in', 'post_parent__not_in',
622 'author__in', 'author__not_in' );
624 foreach ( $array_keys as $key ) {
625 if ( !isset($array[$key]) )
626 $array[$key] = array();
632 * Parse a query string and set query type booleans.
635 * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
636 * array key to `$orderby`.
637 * @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
638 * search terms, by prepending a hyphen.
639 * @since 4.5.0 Removed the `$comments_popup` parameter.
640 * Introduced the `$comment_status` and `$ping_status` parameters.
641 * Introduced `RAND(x)` syntax for `$orderby`, which allows an integer seed value to random sorts.
642 * @since 4.6.0 Added 'post_name__in' support for `$orderby`. Introduced the `$lazy_load_term_meta` argument.
645 * @param string|array $query {
646 * Optional. Array or string of Query parameters.
648 * @type int $attachment_id Attachment post ID. Used for 'attachment' post_type.
649 * @type int|string $author Author ID, or comma-separated list of IDs.
650 * @type string $author_name User 'user_nicename'.
651 * @type array $author__in An array of author IDs to query from.
652 * @type array $author__not_in An array of author IDs not to query from.
653 * @type bool $cache_results Whether to cache post information. Default true.
654 * @type int|string $cat Category ID or comma-separated list of IDs (this or any children).
655 * @type array $category__and An array of category IDs (AND in).
656 * @type array $category__in An array of category IDs (OR in, no children).
657 * @type array $category__not_in An array of category IDs (NOT in).
658 * @type string $category_name Use category slug (not name, this or any children).
659 * @type string $comment_status Comment status.
660 * @type int $comments_per_page The number of comments to return per page.
661 * Default 'comments_per_page' option.
662 * @type array $date_query An associative array of WP_Date_Query arguments.
663 * See WP_Date_Query::__construct().
664 * @type int $day Day of the month. Default empty. Accepts numbers 1-31.
665 * @type bool $exact Whether to search by exact keyword. Default false.
666 * @type string|array $fields Which fields to return. Single field or all fields (string),
667 * or array of fields. 'id=>parent' uses 'id' and 'post_parent'.
668 * Default all fields. Accepts 'ids', 'id=>parent'.
669 * @type int $hour Hour of the day. Default empty. Accepts numbers 0-23.
670 * @type int|bool $ignore_sticky_posts Whether to ignore sticky posts or not. Setting this to false
671 * excludes stickies from 'post__in'. Accepts 1|true, 0|false.
673 * @type int $m Combination YearMonth. Accepts any four-digit year and month
674 * numbers 1-12. Default empty.
675 * @type string $meta_compare Comparison operator to test the 'meta_value'.
676 * @type string $meta_key Custom field key.
677 * @type array $meta_query An associative array of WP_Meta_Query arguments. See WP_Meta_Query.
678 * @type string $meta_value Custom field value.
679 * @type int $meta_value_num Custom field value number.
680 * @type int $menu_order The menu order of the posts.
681 * @type int $monthnum The two-digit month. Default empty. Accepts numbers 1-12.
682 * @type string $name Post slug.
683 * @type bool $nopaging Show all posts (true) or paginate (false). Default false.
684 * @type bool $no_found_rows Whether to skip counting the total rows found. Enabling can improve
685 * performance. Default false.
686 * @type int $offset The number of posts to offset before retrieval.
687 * @type string $order Designates ascending or descending order of posts. Default 'DESC'.
688 * Accepts 'ASC', 'DESC'.
689 * @type string|array $orderby Sort retrieved posts by parameter. One or more options may be
690 * passed. To use 'meta_value', or 'meta_value_num',
691 * 'meta_key=keyname' must be also be defined. To sort by a
692 * specific `$meta_query` clause, use that clause's array key.
693 * Default 'date'. Accepts 'none', 'name', 'author', 'date',
694 * 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand',
695 * 'RAND(x)' (where 'x' is an integer seed value),
696 * 'comment_count', 'meta_value', 'meta_value_num', 'post__in',
697 * 'post_name__in', 'post_parent__in', and the array keys
699 * @type int $p Post ID.
700 * @type int $page Show the number of posts that would show up on page X of a
702 * @type int $paged The number of the current page.
703 * @type int $page_id Page ID.
704 * @type string $pagename Page slug.
705 * @type string $perm Show posts if user has the appropriate capability.
706 * @type string $ping_status Ping status.
707 * @type array $post__in An array of post IDs to retrieve, sticky posts will be included
708 * @type string $post_mime_type The mime type of the post. Used for 'attachment' post_type.
709 * @type array $post__not_in An array of post IDs not to retrieve. Note: a string of comma-
710 * separated IDs will NOT work.
711 * @type int $post_parent Page ID to retrieve child pages for. Use 0 to only retrieve
713 * @type array $post_parent__in An array containing parent page IDs to query child pages from.
714 * @type array $post_parent__not_in An array containing parent page IDs not to query child pages from.
715 * @type string|array $post_type A post type slug (string) or array of post type slugs.
716 * Default 'any' if using 'tax_query'.
717 * @type string|array $post_status A post status (string) or array of post statuses.
718 * @type int $posts_per_page The number of posts to query for. Use -1 to request all posts.
719 * @type int $posts_per_archive_page The number of posts to query for by archive page. Overrides
720 * 'posts_per_page' when is_archive(), or is_search() are true.
721 * @type array $post_name__in An array of post slugs that results must match.
722 * @type string $s Search keyword(s). Prepending a term with a hyphen will
723 * exclude posts matching that term. Eg, 'pillow -sofa' will
724 * return posts containing 'pillow' but not 'sofa'. The
725 * character used for exclusion can be modified using the
726 * the 'wp_query_search_exclusion_prefix' filter.
727 * @type int $second Second of the minute. Default empty. Accepts numbers 0-60.
728 * @type bool $sentence Whether to search by phrase. Default false.
729 * @type bool $suppress_filters Whether to suppress filters. Default false.
730 * @type string $tag Tag slug. Comma-separated (either), Plus-separated (all).
731 * @type array $tag__and An array of tag ids (AND in).
732 * @type array $tag__in An array of tag ids (OR in).
733 * @type array $tag__not_in An array of tag ids (NOT in).
734 * @type int $tag_id Tag id or comma-separated list of IDs.
735 * @type array $tag_slug__and An array of tag slugs (AND in).
736 * @type array $tag_slug__in An array of tag slugs (OR in). unless 'ignore_sticky_posts' is
737 * true. Note: a string of comma-separated IDs will NOT work.
738 * @type array $tax_query An associative array of WP_Tax_Query arguments.
739 * See WP_Tax_Query->queries.
740 * @type string $title Post title.
741 * @type bool $update_post_meta_cache Whether to update the post meta cache. Default true.
742 * @type bool $update_post_term_cache Whether to update the post term cache. Default true.
743 * @type bool $lazy_load_term_meta Whether to lazy-load term meta. Setting to false will
744 * disable cache priming for term meta, so that each
745 * get_term_meta() call will hit the database.
746 * Defaults to the value of `$update_post_term_cache`.
747 * @type int $w The week number of the year. Default empty. Accepts numbers 0-53.
748 * @type int $year The four-digit year. Default empty. Accepts any four-digit year.
751 public function parse_query( $query = '' ) {
752 if ( ! empty( $query ) ) {
754 $this->query = $this->query_vars = wp_parse_args( $query );
755 } elseif ( ! isset( $this->query ) ) {
756 $this->query = $this->query_vars;
759 $this->query_vars = $this->fill_query_vars($this->query_vars);
760 $qv = &$this->query_vars;
761 $this->query_vars_changed = true;
763 if ( ! empty($qv['robots']) )
764 $this->is_robots = true;
766 if ( ! is_scalar( $qv['p'] ) || $qv['p'] < 0 ) {
768 $qv['error'] = '404';
770 $qv['p'] = intval( $qv['p'] );
773 $qv['page_id'] = absint($qv['page_id']);
774 $qv['year'] = absint($qv['year']);
775 $qv['monthnum'] = absint($qv['monthnum']);
776 $qv['day'] = absint($qv['day']);
777 $qv['w'] = absint($qv['w']);
778 $qv['m'] = is_scalar( $qv['m'] ) ? preg_replace( '|[^0-9]|', '', $qv['m'] ) : '';
779 $qv['paged'] = absint($qv['paged']);
780 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
781 $qv['author'] = preg_replace( '|[^0-9,-]|', '', $qv['author'] ); // comma separated list of positive or negative integers
782 $qv['pagename'] = trim( $qv['pagename'] );
783 $qv['name'] = trim( $qv['name'] );
784 $qv['title'] = trim( $qv['title'] );
785 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
786 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
787 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
788 if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']);
790 // Fairly insane upper bound for search string lengths.
791 if ( ! is_scalar( $qv['s'] ) || ( ! empty( $qv['s'] ) && strlen( $qv['s'] ) > 1600 ) ) {
795 // Compat. Map subpost to attachment.
796 if ( '' != $qv['subpost'] )
797 $qv['attachment'] = $qv['subpost'];
798 if ( '' != $qv['subpost_id'] )
799 $qv['attachment_id'] = $qv['subpost_id'];
801 $qv['attachment_id'] = absint($qv['attachment_id']);
803 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
804 $this->is_single = true;
805 $this->is_attachment = true;
806 } elseif ( '' != $qv['name'] ) {
807 $this->is_single = true;
808 } elseif ( $qv['p'] ) {
809 $this->is_single = true;
810 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
811 // If year, month, day, hour, minute, and second are set, a single
812 // post is being queried.
813 $this->is_single = true;
814 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
815 $this->is_page = true;
816 $this->is_single = false;
818 // Look for archive queries. Dates, categories, authors, search, post type archives.
820 if ( isset( $this->query['s'] ) ) {
821 $this->is_search = true;
824 if ( '' !== $qv['second'] ) {
825 $this->is_time = true;
826 $this->is_date = true;
829 if ( '' !== $qv['minute'] ) {
830 $this->is_time = true;
831 $this->is_date = true;
834 if ( '' !== $qv['hour'] ) {
835 $this->is_time = true;
836 $this->is_date = true;
840 if ( ! $this->is_date ) {
841 $date = sprintf( '%04d-%02d-%02d', $qv['year'], $qv['monthnum'], $qv['day'] );
842 if ( $qv['monthnum'] && $qv['year'] && ! wp_checkdate( $qv['monthnum'], $qv['day'], $qv['year'], $date ) ) {
843 $qv['error'] = '404';
845 $this->is_day = true;
846 $this->is_date = true;
851 if ( $qv['monthnum'] ) {
852 if ( ! $this->is_date ) {
853 if ( 12 < $qv['monthnum'] ) {
854 $qv['error'] = '404';
856 $this->is_month = true;
857 $this->is_date = true;
863 if ( ! $this->is_date ) {
864 $this->is_year = true;
865 $this->is_date = true;
870 $this->is_date = true;
871 if ( strlen($qv['m']) > 9 ) {
872 $this->is_time = true;
873 } elseif ( strlen( $qv['m'] ) > 7 ) {
874 $this->is_day = true;
875 } elseif ( strlen( $qv['m'] ) > 5 ) {
876 $this->is_month = true;
878 $this->is_year = true;
882 if ( '' != $qv['w'] ) {
883 $this->is_date = true;
886 $this->query_vars_hash = false;
887 $this->parse_tax_query( $qv );
889 foreach ( $this->tax_query->queries as $tax_query ) {
890 if ( ! is_array( $tax_query ) ) {
894 if ( isset( $tax_query['operator'] ) && 'NOT IN' != $tax_query['operator'] ) {
895 switch ( $tax_query['taxonomy'] ) {
897 $this->is_category = true;
900 $this->is_tag = true;
903 $this->is_tax = true;
909 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
910 $this->is_author = false;
912 $this->is_author = true;
915 if ( '' != $qv['author_name'] )
916 $this->is_author = true;
918 if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) {
919 $post_type_obj = get_post_type_object( $qv['post_type'] );
920 if ( ! empty( $post_type_obj->has_archive ) )
921 $this->is_post_type_archive = true;
924 if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax )
925 $this->is_archive = true;
928 if ( '' != $qv['feed'] )
929 $this->is_feed = true;
931 if ( '' != $qv['embed'] ) {
932 $this->is_embed = true;
935 if ( '' != $qv['tb'] )
936 $this->is_trackback = true;
938 if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) )
939 $this->is_paged = true;
941 // if we're previewing inside the write screen
942 if ( '' != $qv['preview'] )
943 $this->is_preview = true;
946 $this->is_admin = true;
948 if ( false !== strpos($qv['feed'], 'comments-') ) {
949 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
950 $qv['withcomments'] = 1;
953 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
955 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
956 $this->is_comment_feed = true;
958 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_robots ) )
959 $this->is_home = true;
961 // Correct is_* for page_on_front and page_for_posts
962 if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
963 $_query = wp_parse_args($this->query);
964 // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename.
965 if ( isset($_query['pagename']) && '' == $_query['pagename'] )
966 unset($_query['pagename']);
968 unset( $_query['embed'] );
970 if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) {
971 $this->is_page = true;
972 $this->is_home = false;
973 $qv['page_id'] = get_option('page_on_front');
974 // Correct <!--nextpage--> for page_on_front
975 if ( !empty($qv['paged']) ) {
976 $qv['page'] = $qv['paged'];
982 if ( '' != $qv['pagename'] ) {
983 $this->queried_object = get_page_by_path( $qv['pagename'] );
985 if ( $this->queried_object && 'attachment' == $this->queried_object->post_type ) {
986 if ( preg_match( "/^[^%]*%(?:postname)%/", get_option( 'permalink_structure' ) ) ) {
987 // See if we also have a post with the same slug
988 $post = get_page_by_path( $qv['pagename'], OBJECT, 'post' );
990 $this->queried_object = $post;
991 $this->is_page = false;
992 $this->is_single = true;
997 if ( ! empty( $this->queried_object ) ) {
998 $this->queried_object_id = (int) $this->queried_object->ID;
1000 unset( $this->queried_object );
1003 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1004 $this->is_page = false;
1005 $this->is_home = true;
1006 $this->is_posts_page = true;
1010 if ( $qv['page_id'] ) {
1011 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1012 $this->is_page = false;
1013 $this->is_home = true;
1014 $this->is_posts_page = true;
1018 if ( !empty($qv['post_type']) ) {
1019 if ( is_array($qv['post_type']) )
1020 $qv['post_type'] = array_map('sanitize_key', $qv['post_type']);
1022 $qv['post_type'] = sanitize_key($qv['post_type']);
1025 if ( ! empty( $qv['post_status'] ) ) {
1026 if ( is_array( $qv['post_status'] ) )
1027 $qv['post_status'] = array_map('sanitize_key', $qv['post_status']);
1029 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1032 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1033 $this->is_comment_feed = false;
1035 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1036 // Done correcting is_* for page_on_front and page_for_posts
1038 if ( '404' == $qv['error'] )
1041 $this->is_embed = $this->is_embed && ( $this->is_singular || $this->is_404 );
1043 $this->query_vars_hash = md5( serialize( $this->query_vars ) );
1044 $this->query_vars_changed = false;
1047 * Fires after the main query vars have been parsed.
1051 * @param WP_Query &$this The WP_Query instance (passed by reference).
1053 do_action_ref_array( 'parse_query', array( &$this ) );
1057 * Parses various taxonomy related query vars.
1059 * For BC, this method is not marked as protected. See [28987].
1064 * @param array $q The query variables. Passed by reference.
1066 public function parse_tax_query( &$q ) {
1067 if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) {
1068 $tax_query = $q['tax_query'];
1070 $tax_query = array();
1073 if ( !empty($q['taxonomy']) && !empty($q['term']) ) {
1074 $tax_query[] = array(
1075 'taxonomy' => $q['taxonomy'],
1076 'terms' => array( $q['term'] ),
1081 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t ) {
1082 if ( 'post_tag' == $taxonomy )
1083 continue; // Handled further down in the $q['tag'] block
1085 if ( $t->query_var && !empty( $q[$t->query_var] ) ) {
1086 $tax_query_defaults = array(
1087 'taxonomy' => $taxonomy,
1091 if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) {
1092 $q[$t->query_var] = wp_basename( $q[$t->query_var] );
1095 $term = $q[$t->query_var];
1097 if ( is_array( $term ) ) {
1098 $term = implode( ',', $term );
1101 if ( strpos($term, '+') !== false ) {
1102 $terms = preg_split( '/[+]+/', $term );
1103 foreach ( $terms as $term ) {
1104 $tax_query[] = array_merge( $tax_query_defaults, array(
1105 'terms' => array( $term )
1109 $tax_query[] = array_merge( $tax_query_defaults, array(
1110 'terms' => preg_split( '/[,]+/', $term )
1116 // If querystring 'cat' is an array, implode it.
1117 if ( is_array( $q['cat'] ) ) {
1118 $q['cat'] = implode( ',', $q['cat'] );
1122 if ( ! empty( $q['cat'] ) && ! $this->is_singular ) {
1123 $cat_in = $cat_not_in = array();
1125 $cat_array = preg_split( '/[,\s]+/', urldecode( $q['cat'] ) );
1126 $cat_array = array_map( 'intval', $cat_array );
1127 $q['cat'] = implode( ',', $cat_array );
1129 foreach ( $cat_array as $cat ) {
1133 $cat_not_in[] = abs( $cat );
1136 if ( ! empty( $cat_in ) ) {
1137 $tax_query[] = array(
1138 'taxonomy' => 'category',
1140 'field' => 'term_id',
1141 'include_children' => true
1145 if ( ! empty( $cat_not_in ) ) {
1146 $tax_query[] = array(
1147 'taxonomy' => 'category',
1148 'terms' => $cat_not_in,
1149 'field' => 'term_id',
1150 'operator' => 'NOT IN',
1151 'include_children' => true
1154 unset( $cat_array, $cat_in, $cat_not_in );
1157 if ( ! empty( $q['category__and'] ) && 1 === count( (array) $q['category__and'] ) ) {
1158 $q['category__and'] = (array) $q['category__and'];
1159 if ( ! isset( $q['category__in'] ) )
1160 $q['category__in'] = array();
1161 $q['category__in'][] = absint( reset( $q['category__and'] ) );
1162 unset( $q['category__and'] );
1165 if ( ! empty( $q['category__in'] ) ) {
1166 $q['category__in'] = array_map( 'absint', array_unique( (array) $q['category__in'] ) );
1167 $tax_query[] = array(
1168 'taxonomy' => 'category',
1169 'terms' => $q['category__in'],
1170 'field' => 'term_id',
1171 'include_children' => false
1175 if ( ! empty($q['category__not_in']) ) {
1176 $q['category__not_in'] = array_map( 'absint', array_unique( (array) $q['category__not_in'] ) );
1177 $tax_query[] = array(
1178 'taxonomy' => 'category',
1179 'terms' => $q['category__not_in'],
1180 'operator' => 'NOT IN',
1181 'include_children' => false
1185 if ( ! empty($q['category__and']) ) {
1186 $q['category__and'] = array_map( 'absint', array_unique( (array) $q['category__and'] ) );
1187 $tax_query[] = array(
1188 'taxonomy' => 'category',
1189 'terms' => $q['category__and'],
1190 'field' => 'term_id',
1191 'operator' => 'AND',
1192 'include_children' => false
1196 // If querystring 'tag' is array, implode it.
1197 if ( is_array( $q['tag'] ) ) {
1198 $q['tag'] = implode( ',', $q['tag'] );
1202 if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) {
1203 if ( strpos($q['tag'], ',') !== false ) {
1204 $tags = preg_split('/[,\r\n\t ]+/', $q['tag']);
1205 foreach ( (array) $tags as $tag ) {
1206 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1207 $q['tag_slug__in'][] = $tag;
1209 } elseif ( preg_match('/[+\r\n\t ]+/', $q['tag'] ) || ! empty( $q['cat'] ) ) {
1210 $tags = preg_split('/[+\r\n\t ]+/', $q['tag']);
1211 foreach ( (array) $tags as $tag ) {
1212 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1213 $q['tag_slug__and'][] = $tag;
1216 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1217 $q['tag_slug__in'][] = $q['tag'];
1221 if ( !empty($q['tag_id']) ) {
1222 $q['tag_id'] = absint( $q['tag_id'] );
1223 $tax_query[] = array(
1224 'taxonomy' => 'post_tag',
1225 'terms' => $q['tag_id']
1229 if ( !empty($q['tag__in']) ) {
1230 $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) );
1231 $tax_query[] = array(
1232 'taxonomy' => 'post_tag',
1233 'terms' => $q['tag__in']
1237 if ( !empty($q['tag__not_in']) ) {
1238 $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) );
1239 $tax_query[] = array(
1240 'taxonomy' => 'post_tag',
1241 'terms' => $q['tag__not_in'],
1242 'operator' => 'NOT IN'
1246 if ( !empty($q['tag__and']) ) {
1247 $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) );
1248 $tax_query[] = array(
1249 'taxonomy' => 'post_tag',
1250 'terms' => $q['tag__and'],
1255 if ( !empty($q['tag_slug__in']) ) {
1256 $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) );
1257 $tax_query[] = array(
1258 'taxonomy' => 'post_tag',
1259 'terms' => $q['tag_slug__in'],
1264 if ( !empty($q['tag_slug__and']) ) {
1265 $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) );
1266 $tax_query[] = array(
1267 'taxonomy' => 'post_tag',
1268 'terms' => $q['tag_slug__and'],
1274 $this->tax_query = new WP_Tax_Query( $tax_query );
1277 * Fires after taxonomy-related query vars have been parsed.
1281 * @param WP_Query $this The WP_Query instance.
1283 do_action( 'parse_tax_query', $this );
1287 * Generate SQL for the WHERE clause based on passed search terms.
1291 * @param array $q Query variables.
1292 * @return string WHERE clause.
1294 protected function parse_search( &$q ) {
1299 // added slashes screw with quote grouping when done early, so done later
1300 $q['s'] = stripslashes( $q['s'] );
1301 if ( empty( $_GET['s'] ) && $this->is_main_query() )
1302 $q['s'] = urldecode( $q['s'] );
1303 // there are no line breaks in <input /> fields
1304 $q['s'] = str_replace( array( "\r", "\n" ), '', $q['s'] );
1305 $q['search_terms_count'] = 1;
1306 if ( ! empty( $q['sentence'] ) ) {
1307 $q['search_terms'] = array( $q['s'] );
1309 if ( preg_match_all( '/".*?("|$)|((?<=[\t ",+])|^)[^\t ",+]+/', $q['s'], $matches ) ) {
1310 $q['search_terms_count'] = count( $matches[0] );
1311 $q['search_terms'] = $this->parse_search_terms( $matches[0] );
1312 // if the search string has only short terms or stopwords, or is 10+ terms long, match it as sentence
1313 if ( empty( $q['search_terms'] ) || count( $q['search_terms'] ) > 9 )
1314 $q['search_terms'] = array( $q['s'] );
1316 $q['search_terms'] = array( $q['s'] );
1320 $n = ! empty( $q['exact'] ) ? '' : '%';
1322 $q['search_orderby_title'] = array();
1325 * Filters the prefix that indicates that a search term should be excluded from results.
1329 * @param string $exclusion_prefix The prefix. Default '-'. Returning
1330 * an empty value disables exclusions.
1332 $exclusion_prefix = apply_filters( 'wp_query_search_exclusion_prefix', '-' );
1334 foreach ( $q['search_terms'] as $term ) {
1335 // If there is an $exclusion_prefix, terms prefixed with it should be excluded.
1336 $exclude = $exclusion_prefix && ( $exclusion_prefix === substr( $term, 0, 1 ) );
1338 $like_op = 'NOT LIKE';
1340 $term = substr( $term, 1 );
1346 if ( $n && ! $exclude ) {
1347 $like = '%' . $wpdb->esc_like( $term ) . '%';
1348 $q['search_orderby_title'][] = $wpdb->prepare( "{$wpdb->posts}.post_title LIKE %s", $like );
1351 $like = $n . $wpdb->esc_like( $term ) . $n;
1352 $search .= $wpdb->prepare( "{$searchand}(({$wpdb->posts}.post_title $like_op %s) $andor_op ({$wpdb->posts}.post_excerpt $like_op %s) $andor_op ({$wpdb->posts}.post_content $like_op %s))", $like, $like, $like );
1353 $searchand = ' AND ';
1356 if ( ! empty( $search ) ) {
1357 $search = " AND ({$search}) ";
1358 if ( ! is_user_logged_in() ) {
1359 $search .= " AND ({$wpdb->posts}.post_password = '') ";
1367 * Check if the terms are suitable for searching.
1369 * Uses an array of stopwords (terms) that are excluded from the separate
1370 * term matching when searching for posts. The list of English stopwords is
1371 * the approximate search engines list, and is translatable.
1375 * @param array $terms Terms to check.
1376 * @return array Terms that are not stopwords.
1378 protected function parse_search_terms( $terms ) {
1379 $strtolower = function_exists( 'mb_strtolower' ) ? 'mb_strtolower' : 'strtolower';
1382 $stopwords = $this->get_search_stopwords();
1384 foreach ( $terms as $term ) {
1385 // keep before/after spaces when term is for exact match
1386 if ( preg_match( '/^".+"$/', $term ) )
1387 $term = trim( $term, "\"'" );
1389 $term = trim( $term, "\"' " );
1391 // Avoid single A-Z and single dashes.
1392 if ( ! $term || ( 1 === strlen( $term ) && preg_match( '/^[a-z\-]$/i', $term ) ) )
1395 if ( in_array( call_user_func( $strtolower, $term ), $stopwords, true ) )
1405 * Retrieve stopwords used when parsing search terms.
1409 * @return array Stopwords.
1411 protected function get_search_stopwords() {
1412 if ( isset( $this->stopwords ) )
1413 return $this->stopwords;
1415 /* translators: This is a comma-separated list of very common words that should be excluded from a search,
1416 * like a, an, and the. These are usually called "stopwords". You should not simply translate these individual
1417 * words into your language. Instead, look for and provide commonly accepted stopwords in your language.
1419 $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',
1420 'Comma-separated list of search stopwords in your language' ) );
1422 $stopwords = array();
1423 foreach ( $words as $word ) {
1424 $word = trim( $word, "\r\n\t " );
1426 $stopwords[] = $word;
1430 * Filters stopwords used when parsing search terms.
1434 * @param array $stopwords Stopwords.
1436 $this->stopwords = apply_filters( 'wp_search_stopwords', $stopwords );
1437 return $this->stopwords;
1441 * Generate SQL for the ORDER BY condition based on passed search terms.
1443 * @param array $q Query variables.
1444 * @return string ORDER BY clause.
1446 protected function parse_search_order( &$q ) {
1449 if ( $q['search_terms_count'] > 1 ) {
1450 $num_terms = count( $q['search_orderby_title'] );
1452 // If the search terms contain negative queries, don't bother ordering by sentence matches.
1454 if ( ! preg_match( '/(?:\s|^)\-/', $q['s'] ) ) {
1455 $like = '%' . $wpdb->esc_like( $q['s'] ) . '%';
1458 $search_orderby = '';
1460 // sentence match in 'post_title'
1462 $search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_title LIKE %s THEN 1 ", $like );
1465 // sanity limit, sort as sentence when more than 6 terms
1466 // (few searches are longer than 6 terms and most titles are not)
1467 if ( $num_terms < 7 ) {
1468 // all words in title
1469 $search_orderby .= 'WHEN ' . implode( ' AND ', $q['search_orderby_title'] ) . ' THEN 2 ';
1470 // any word in title, not needed when $num_terms == 1
1471 if ( $num_terms > 1 )
1472 $search_orderby .= 'WHEN ' . implode( ' OR ', $q['search_orderby_title'] ) . ' THEN 3 ';
1475 // Sentence match in 'post_content' and 'post_excerpt'.
1477 $search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_excerpt LIKE %s THEN 4 ", $like );
1478 $search_orderby .= $wpdb->prepare( "WHEN {$wpdb->posts}.post_content LIKE %s THEN 5 ", $like );
1481 if ( $search_orderby ) {
1482 $search_orderby = '(CASE ' . $search_orderby . 'ELSE 6 END)';
1485 // single word or sentence search
1486 $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC';
1489 return $search_orderby;
1493 * If the passed orderby value is allowed, convert the alias to a
1494 * properly-prefixed orderby value.
1499 * @param string $orderby Alias for the field to order by.
1500 * @return string|false Table-prefixed value to used in the ORDER clause. False otherwise.
1502 protected function parse_orderby( $orderby ) {
1505 // Used to filter values.
1506 $allowed_keys = array(
1507 'post_name', 'post_author', 'post_date', 'post_title', 'post_modified',
1508 'post_parent', 'post_type', 'name', 'author', 'date', 'title', 'modified',
1509 'parent', 'type', 'ID', 'menu_order', 'comment_count', 'rand',
1512 $primary_meta_key = '';
1513 $primary_meta_query = false;
1514 $meta_clauses = $this->meta_query->get_clauses();
1515 if ( ! empty( $meta_clauses ) ) {
1516 $primary_meta_query = reset( $meta_clauses );
1518 if ( ! empty( $primary_meta_query['key'] ) ) {
1519 $primary_meta_key = $primary_meta_query['key'];
1520 $allowed_keys[] = $primary_meta_key;
1523 $allowed_keys[] = 'meta_value';
1524 $allowed_keys[] = 'meta_value_num';
1525 $allowed_keys = array_merge( $allowed_keys, array_keys( $meta_clauses ) );
1528 // If RAND() contains a seed value, sanitize and add to allowed keys.
1529 $rand_with_seed = false;
1530 if ( preg_match( '/RAND\(([0-9]+)\)/i', $orderby, $matches ) ) {
1531 $orderby = sprintf( 'RAND(%s)', intval( $matches[1] ) );
1532 $allowed_keys[] = $orderby;
1533 $rand_with_seed = true;
1536 if ( ! in_array( $orderby, $allowed_keys, true ) ) {
1540 switch ( $orderby ) {
1545 case 'post_modified':
1550 case 'comment_count':
1551 $orderby_clause = "{$wpdb->posts}.{$orderby}";
1554 $orderby_clause = 'RAND()';
1556 case $primary_meta_key:
1558 if ( ! empty( $primary_meta_query['type'] ) ) {
1559 $orderby_clause = "CAST({$primary_meta_query['alias']}.meta_value AS {$primary_meta_query['cast']})";
1561 $orderby_clause = "{$primary_meta_query['alias']}.meta_value";
1564 case 'meta_value_num':
1565 $orderby_clause = "{$primary_meta_query['alias']}.meta_value+0";
1568 if ( array_key_exists( $orderby, $meta_clauses ) ) {
1569 // $orderby corresponds to a meta_query clause.
1570 $meta_clause = $meta_clauses[ $orderby ];
1571 $orderby_clause = "CAST({$meta_clause['alias']}.meta_value AS {$meta_clause['cast']})";
1572 } elseif ( $rand_with_seed ) {
1573 $orderby_clause = $orderby;
1575 // Default: order by post field.
1576 $orderby_clause = "{$wpdb->posts}.post_" . sanitize_key( $orderby );
1582 return $orderby_clause;
1586 * Parse an 'order' query variable and cast it to ASC or DESC as necessary.
1591 * @param string $order The 'order' query variable.
1592 * @return string The sanitized 'order' query variable.
1594 protected function parse_order( $order ) {
1595 if ( ! is_string( $order ) || empty( $order ) ) {
1599 if ( 'ASC' === strtoupper( $order ) ) {
1607 * Sets the 404 property and saves whether query is feed.
1612 public function set_404() {
1613 $is_feed = $this->is_feed;
1615 $this->init_query_flags();
1616 $this->is_404 = true;
1618 $this->is_feed = $is_feed;
1622 * Retrieve query variable.
1625 * @since 3.9.0 The `$default` argument was introduced.
1629 * @param string $query_var Query variable key.
1630 * @param mixed $default Optional. Value to return if the query variable is not set. Default empty.
1631 * @return mixed Contents of the query variable.
1633 public function get( $query_var, $default = '' ) {
1634 if ( isset( $this->query_vars[ $query_var ] ) ) {
1635 return $this->query_vars[ $query_var ];
1642 * Set query variable.
1647 * @param string $query_var Query variable key.
1648 * @param mixed $value Query variable value.
1650 public function set($query_var, $value) {
1651 $this->query_vars[$query_var] = $value;
1655 * Retrieve the posts based on query variables.
1657 * There are a few filters and actions that can be used to modify the post
1663 * @return array List of posts.
1665 public function get_posts() {
1668 $this->parse_query();
1671 * Fires after the query variable object is created, but before the actual query is run.
1673 * Note: If using conditional tags, use the method versions within the passed instance
1674 * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions
1675 * like is_main_query() test against the global $wp_query instance, not the passed one.
1679 * @param WP_Query &$this The WP_Query instance (passed by reference).
1681 do_action_ref_array( 'pre_get_posts', array( &$this ) );
1684 $q = &$this->query_vars;
1686 // Fill again in case pre_get_posts unset some vars.
1687 $q = $this->fill_query_vars($q);
1690 $this->meta_query = new WP_Meta_Query();
1691 $this->meta_query->parse_query_vars( $q );
1693 // Set a flag if a pre_get_posts hook changed the query vars.
1694 $hash = md5( serialize( $this->query_vars ) );
1695 if ( $hash != $this->query_vars_hash ) {
1696 $this->query_vars_changed = true;
1697 $this->query_vars_hash = $hash;
1701 // First let's clear some variables
1704 $whichmimetype = '';
1710 $post_status_join = false;
1713 if ( isset( $q['caller_get_posts'] ) ) {
1714 _deprecated_argument( 'WP_Query', '3.1.0', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) );
1715 if ( !isset( $q['ignore_sticky_posts'] ) )
1716 $q['ignore_sticky_posts'] = $q['caller_get_posts'];
1719 if ( !isset( $q['ignore_sticky_posts'] ) )
1720 $q['ignore_sticky_posts'] = false;
1722 if ( !isset($q['suppress_filters']) )
1723 $q['suppress_filters'] = false;
1725 if ( !isset($q['cache_results']) ) {
1726 if ( wp_using_ext_object_cache() )
1727 $q['cache_results'] = false;
1729 $q['cache_results'] = true;
1732 if ( !isset($q['update_post_term_cache']) )
1733 $q['update_post_term_cache'] = true;
1735 if ( ! isset( $q['lazy_load_term_meta'] ) ) {
1736 $q['lazy_load_term_meta'] = $q['update_post_term_cache'];
1739 if ( !isset($q['update_post_meta_cache']) )
1740 $q['update_post_meta_cache'] = true;
1742 if ( !isset($q['post_type']) ) {
1743 if ( $this->is_search )
1744 $q['post_type'] = 'any';
1746 $q['post_type'] = '';
1748 $post_type = $q['post_type'];
1749 if ( empty( $q['posts_per_page'] ) ) {
1750 $q['posts_per_page'] = get_option( 'posts_per_page' );
1752 if ( isset($q['showposts']) && $q['showposts'] ) {
1753 $q['showposts'] = (int) $q['showposts'];
1754 $q['posts_per_page'] = $q['showposts'];
1756 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
1757 $q['posts_per_page'] = $q['posts_per_archive_page'];
1758 if ( !isset($q['nopaging']) ) {
1759 if ( $q['posts_per_page'] == -1 ) {
1760 $q['nopaging'] = true;
1762 $q['nopaging'] = false;
1766 if ( $this->is_feed ) {
1767 // This overrides posts_per_page.
1768 if ( ! empty( $q['posts_per_rss'] ) ) {
1769 $q['posts_per_page'] = $q['posts_per_rss'];
1771 $q['posts_per_page'] = get_option( 'posts_per_rss' );
1773 $q['nopaging'] = false;
1775 $q['posts_per_page'] = (int) $q['posts_per_page'];
1776 if ( $q['posts_per_page'] < -1 )
1777 $q['posts_per_page'] = abs($q['posts_per_page']);
1778 elseif ( $q['posts_per_page'] == 0 )
1779 $q['posts_per_page'] = 1;
1781 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
1782 $q['comments_per_page'] = get_option('comments_per_page');
1784 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
1785 $this->is_page = true;
1786 $this->is_home = false;
1787 $q['page_id'] = get_option('page_on_front');
1790 if ( isset($q['page']) ) {
1791 $q['page'] = trim($q['page'], '/');
1792 $q['page'] = absint($q['page']);
1795 // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
1796 if ( isset($q['no_found_rows']) )
1797 $q['no_found_rows'] = (bool) $q['no_found_rows'];
1799 $q['no_found_rows'] = false;
1801 switch ( $q['fields'] ) {
1803 $fields = "{$wpdb->posts}.ID";
1806 $fields = "{$wpdb->posts}.ID, {$wpdb->posts}.post_parent";
1809 $fields = "{$wpdb->posts}.*";
1812 if ( '' !== $q['menu_order'] ) {
1813 $where .= " AND {$wpdb->posts}.menu_order = " . $q['menu_order'];
1815 // The "m" parameter is meant for months but accepts datetimes of varying specificity
1817 $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
1818 if ( strlen($q['m']) > 5 ) {
1819 $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
1821 if ( strlen($q['m']) > 7 ) {
1822 $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
1824 if ( strlen($q['m']) > 9 ) {
1825 $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
1827 if ( strlen($q['m']) > 11 ) {
1828 $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
1830 if ( strlen($q['m']) > 13 ) {
1831 $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
1835 // Handle the other individual date parameters
1836 $date_parameters = array();
1838 if ( '' !== $q['hour'] )
1839 $date_parameters['hour'] = $q['hour'];
1841 if ( '' !== $q['minute'] )
1842 $date_parameters['minute'] = $q['minute'];
1844 if ( '' !== $q['second'] )
1845 $date_parameters['second'] = $q['second'];
1848 $date_parameters['year'] = $q['year'];
1850 if ( $q['monthnum'] )
1851 $date_parameters['monthnum'] = $q['monthnum'];
1854 $date_parameters['week'] = $q['w'];
1857 $date_parameters['day'] = $q['day'];
1859 if ( $date_parameters ) {
1860 $date_query = new WP_Date_Query( array( $date_parameters ) );
1861 $where .= $date_query->get_sql();
1863 unset( $date_parameters, $date_query );
1865 // Handle complex date queries
1866 if ( ! empty( $q['date_query'] ) ) {
1867 $this->date_query = new WP_Date_Query( $q['date_query'] );
1868 $where .= $this->date_query->get_sql();
1872 // If we've got a post_type AND it's not "any" post_type.
1873 if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) {
1874 foreach ( (array)$q['post_type'] as $_post_type ) {
1875 $ptype_obj = get_post_type_object($_post_type);
1876 if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) )
1879 if ( ! $ptype_obj->hierarchical ) {
1880 // Non-hierarchical post types can directly use 'name'.
1881 $q['name'] = $q[ $ptype_obj->query_var ];
1883 // Hierarchical post types will operate through 'pagename'.
1884 $q['pagename'] = $q[ $ptype_obj->query_var ];
1888 // Only one request for a slug is possible, this is why name & pagename are overwritten above.
1894 if ( '' !== $q['title'] ) {
1895 $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_title = %s", stripslashes( $q['title'] ) );
1898 // Parameters related to 'post_name'.
1899 if ( '' != $q['name'] ) {
1900 $q['name'] = sanitize_title_for_query( $q['name'] );
1901 $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'";
1902 } elseif ( '' != $q['pagename'] ) {
1903 if ( isset($this->queried_object_id) ) {
1904 $reqpage = $this->queried_object_id;
1906 if ( 'page' != $q['post_type'] ) {
1907 foreach ( (array)$q['post_type'] as $_post_type ) {
1908 $ptype_obj = get_post_type_object($_post_type);
1909 if ( !$ptype_obj || !$ptype_obj->hierarchical )
1912 $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
1918 $reqpage = get_page_by_path($q['pagename']);
1920 if ( !empty($reqpage) )
1921 $reqpage = $reqpage->ID;
1926 $page_for_posts = get_option('page_for_posts');
1927 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
1928 $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) );
1929 $q['name'] = $q['pagename'];
1930 $where .= " AND ({$wpdb->posts}.ID = '$reqpage')";
1931 $reqpage_obj = get_post( $reqpage );
1932 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
1933 $this->is_attachment = true;
1934 $post_type = $q['post_type'] = 'attachment';
1935 $this->is_page = true;
1936 $q['attachment_id'] = $reqpage;
1939 } elseif ( '' != $q['attachment'] ) {
1940 $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) );
1941 $q['name'] = $q['attachment'];
1942 $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
1943 } elseif ( is_array( $q['post_name__in'] ) && ! empty( $q['post_name__in'] ) ) {
1944 $q['post_name__in'] = array_map( 'sanitize_title_for_query', $q['post_name__in'] );
1945 $post_name__in = "'" . implode( "','", $q['post_name__in'] ) . "'";
1946 $where .= " AND {$wpdb->posts}.post_name IN ($post_name__in)";
1949 // If an attachment is requested by number, let it supersede any post number.
1950 if ( $q['attachment_id'] )
1951 $q['p'] = absint($q['attachment_id']);
1953 // If a post number is specified, load that post
1955 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
1956 } elseif ( $q['post__in'] ) {
1957 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
1958 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
1959 } elseif ( $q['post__not_in'] ) {
1960 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
1961 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
1964 if ( is_numeric( $q['post_parent'] ) ) {
1965 $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_parent = %d ", $q['post_parent'] );
1966 } elseif ( $q['post_parent__in'] ) {
1967 $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) );
1968 $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)";
1969 } elseif ( $q['post_parent__not_in'] ) {
1970 $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) );
1971 $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)";
1974 if ( $q['page_id'] ) {
1975 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
1976 $q['p'] = $q['page_id'];
1977 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
1981 // If a search pattern is specified, load the posts that match.
1982 if ( strlen( $q['s'] ) ) {
1983 $search = $this->parse_search( $q );
1986 if ( ! $q['suppress_filters'] ) {
1988 * Filters the search SQL that is used in the WHERE clause of WP_Query.
1992 * @param string $search Search SQL for WHERE clause.
1993 * @param WP_Query $this The current WP_Query object.
1995 $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) );
1999 if ( !$this->is_singular ) {
2000 $this->parse_tax_query( $q );
2002 $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' );
2004 $join .= $clauses['join'];
2005 $where .= $clauses['where'];
2008 if ( $this->is_tax ) {
2009 if ( empty($post_type) ) {
2010 // Do a fully inclusive search for currently registered post types of queried taxonomies
2011 $post_type = array();
2012 $taxonomies = array_keys( $this->tax_query->queried_terms );
2013 foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) {
2014 $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt );
2015 if ( array_intersect( $taxonomies, $object_taxonomies ) )
2020 elseif ( count( $post_type ) == 1 )
2021 $post_type = $post_type[0];
2023 $post_status_join = true;
2024 } elseif ( in_array('attachment', (array) $post_type) ) {
2025 $post_status_join = true;
2030 * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and
2031 * 'category_name' vars are set for backward compatibility.
2033 if ( ! empty( $this->tax_query->queried_terms ) ) {
2036 * Set 'taxonomy', 'term', and 'term_id' to the
2037 * first taxonomy other than 'post_tag' or 'category'.
2039 if ( ! isset( $q['taxonomy'] ) ) {
2040 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2041 if ( empty( $queried_items['terms'][0] ) ) {
2045 if ( ! in_array( $queried_taxonomy, array( 'category', 'post_tag' ) ) ) {
2046 $q['taxonomy'] = $queried_taxonomy;
2048 if ( 'slug' === $queried_items['field'] ) {
2049 $q['term'] = $queried_items['terms'][0];
2051 $q['term_id'] = $queried_items['terms'][0];
2054 // Take the first one we find.
2060 // 'cat', 'category_name', 'tag_id'
2061 foreach ( $this->tax_query->queried_terms as $queried_taxonomy => $queried_items ) {
2062 if ( empty( $queried_items['terms'][0] ) ) {
2066 if ( 'category' === $queried_taxonomy ) {
2067 $the_cat = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'category' );
2069 $this->set( 'cat', $the_cat->term_id );
2070 $this->set( 'category_name', $the_cat->slug );
2075 if ( 'post_tag' === $queried_taxonomy ) {
2076 $the_tag = get_term_by( $queried_items['field'], $queried_items['terms'][0], 'post_tag' );
2078 $this->set( 'tag_id', $the_tag->term_id );
2085 if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) {
2086 $groupby = "{$wpdb->posts}.ID";
2089 // Author/user stuff
2091 if ( ! empty( $q['author'] ) && $q['author'] != '0' ) {
2092 $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) );
2093 $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) );
2094 foreach ( $authors as $author ) {
2095 $key = $author > 0 ? 'author__in' : 'author__not_in';
2096 $q[$key][] = abs( $author );
2098 $q['author'] = implode( ',', $authors );
2101 if ( ! empty( $q['author__not_in'] ) ) {
2102 $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) );
2103 $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) ";
2104 } elseif ( ! empty( $q['author__in'] ) ) {
2105 $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) );
2106 $where .= " AND {$wpdb->posts}.post_author IN ($author__in) ";
2109 // Author stuff for nice URLs
2111 if ( '' != $q['author_name'] ) {
2112 if ( strpos($q['author_name'], '/') !== false ) {
2113 $q['author_name'] = explode('/', $q['author_name']);
2114 if ( $q['author_name'][ count($q['author_name'])-1 ] ) {
2115 $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash
2117 $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash
2120 $q['author_name'] = sanitize_title_for_query( $q['author_name'] );
2121 $q['author'] = get_user_by('slug', $q['author_name']);
2123 $q['author'] = $q['author']->ID;
2124 $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')';
2127 // MIME-Type stuff for attachment browsing
2129 if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] ) {
2130 $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts );
2132 $where .= $search . $whichauthor . $whichmimetype;
2134 if ( ! empty( $this->meta_query->queries ) ) {
2135 $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this );
2136 $join .= $clauses['join'];
2137 $where .= $clauses['where'];
2140 $rand = ( isset( $q['orderby'] ) && 'rand' === $q['orderby'] );
2141 if ( ! isset( $q['order'] ) ) {
2142 $q['order'] = $rand ? '' : 'DESC';
2144 $q['order'] = $rand ? '' : $this->parse_order( $q['order'] );
2148 if ( empty( $q['orderby'] ) ) {
2150 * Boolean false or empty array blanks out ORDER BY,
2151 * while leaving the value unset or otherwise empty sets the default.
2153 if ( isset( $q['orderby'] ) && ( is_array( $q['orderby'] ) || false === $q['orderby'] ) ) {
2156 $orderby = "{$wpdb->posts}.post_date " . $q['order'];
2158 } elseif ( 'none' == $q['orderby'] ) {
2160 } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) {
2161 $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )";
2162 } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) {
2163 $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )";
2164 } elseif ( $q['orderby'] == 'post_name__in' && ! empty( $post_name__in ) ) {
2165 $orderby = "FIELD( {$wpdb->posts}.post_name, $post_name__in )";
2167 $orderby_array = array();
2168 if ( is_array( $q['orderby'] ) ) {
2169 foreach ( $q['orderby'] as $_orderby => $order ) {
2170 $orderby = addslashes_gpc( urldecode( $_orderby ) );
2171 $parsed = $this->parse_orderby( $orderby );
2177 $orderby_array[] = $parsed . ' ' . $this->parse_order( $order );
2179 $orderby = implode( ', ', $orderby_array );
2182 $q['orderby'] = urldecode( $q['orderby'] );
2183 $q['orderby'] = addslashes_gpc( $q['orderby'] );
2185 foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) {
2186 $parsed = $this->parse_orderby( $orderby );
2187 // Only allow certain values for safety.
2192 $orderby_array[] = $parsed;
2194 $orderby = implode( ' ' . $q['order'] . ', ', $orderby_array );
2196 if ( empty( $orderby ) ) {
2197 $orderby = "{$wpdb->posts}.post_date " . $q['order'];
2198 } elseif ( ! empty( $q['order'] ) ) {
2199 $orderby .= " {$q['order']}";
2204 // Order search results by relevance only when another "orderby" is not specified in the query.
2205 if ( ! empty( $q['s'] ) ) {
2206 $search_orderby = '';
2207 if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) )
2208 $search_orderby = $this->parse_search_order( $q );
2210 if ( ! $q['suppress_filters'] ) {
2212 * Filters the ORDER BY used when ordering search results.
2216 * @param string $search_orderby The ORDER BY clause.
2217 * @param WP_Query $this The current WP_Query instance.
2219 $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this );
2222 if ( $search_orderby )
2223 $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby;
2226 if ( is_array( $post_type ) && count( $post_type ) > 1 ) {
2227 $post_type_cap = 'multiple_post_type';
2229 if ( is_array( $post_type ) )
2230 $post_type = reset( $post_type );
2231 $post_type_object = get_post_type_object( $post_type );
2232 if ( empty( $post_type_object ) )
2233 $post_type_cap = $post_type;
2236 if ( isset( $q['post_password'] ) ) {
2237 $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_password = %s", $q['post_password'] );
2238 if ( empty( $q['perm'] ) ) {
2239 $q['perm'] = 'readable';
2241 } elseif ( isset( $q['has_password'] ) ) {
2242 $where .= sprintf( " AND {$wpdb->posts}.post_password %s ''", $q['has_password'] ? '!=' : '=' );
2245 if ( ! empty( $q['comment_status'] ) ) {
2246 $where .= $wpdb->prepare( " AND {$wpdb->posts}.comment_status = %s ", $q['comment_status'] );
2249 if ( ! empty( $q['ping_status'] ) ) {
2250 $where .= $wpdb->prepare( " AND {$wpdb->posts}.ping_status = %s ", $q['ping_status'] );
2253 if ( 'any' == $post_type ) {
2254 $in_search_post_types = get_post_types( array('exclude_from_search' => false) );
2255 if ( empty( $in_search_post_types ) ) {
2256 $where .= ' AND 1=0 ';
2258 $where .= " AND {$wpdb->posts}.post_type IN ('" . join( "', '", array_map( 'esc_sql', $in_search_post_types ) ) . "')";
2260 } elseif ( !empty( $post_type ) && is_array( $post_type ) ) {
2261 $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", esc_sql( $post_type ) ) . "')";
2262 } elseif ( ! empty( $post_type ) ) {
2263 $where .= $wpdb->prepare( " AND {$wpdb->posts}.post_type = %s", $post_type );
2264 $post_type_object = get_post_type_object ( $post_type );
2265 } elseif ( $this->is_attachment ) {
2266 $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
2267 $post_type_object = get_post_type_object ( 'attachment' );
2268 } elseif ( $this->is_page ) {
2269 $where .= " AND {$wpdb->posts}.post_type = 'page'";
2270 $post_type_object = get_post_type_object ( 'page' );
2272 $where .= " AND {$wpdb->posts}.post_type = 'post'";
2273 $post_type_object = get_post_type_object ( 'post' );
2276 $edit_cap = 'edit_post';
2277 $read_cap = 'read_post';
2279 if ( ! empty( $post_type_object ) ) {
2280 $edit_others_cap = $post_type_object->cap->edit_others_posts;
2281 $read_private_cap = $post_type_object->cap->read_private_posts;
2283 $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
2284 $read_private_cap = 'read_private_' . $post_type_cap . 's';
2287 $user_id = get_current_user_id();
2289 $q_status = array();
2290 if ( ! empty( $q['post_status'] ) ) {
2291 $statuswheres = array();
2292 $q_status = $q['post_status'];
2293 if ( ! is_array( $q_status ) )
2294 $q_status = explode(',', $q_status);
2295 $r_status = array();
2296 $p_status = array();
2297 $e_status = array();
2298 if ( in_array( 'any', $q_status ) ) {
2299 foreach ( get_post_stati( array( 'exclude_from_search' => true ) ) as $status ) {
2300 if ( ! in_array( $status, $q_status ) ) {
2301 $e_status[] = "{$wpdb->posts}.post_status <> '$status'";
2305 foreach ( get_post_stati() as $status ) {
2306 if ( in_array( $status, $q_status ) ) {
2307 if ( 'private' == $status ) {
2308 $p_status[] = "{$wpdb->posts}.post_status = '$status'";
2310 $r_status[] = "{$wpdb->posts}.post_status = '$status'";
2316 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
2317 $r_status = array_merge($r_status, $p_status);
2321 if ( !empty($e_status) ) {
2322 $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")";
2324 if ( !empty($r_status) ) {
2325 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) ) {
2326 $statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))";
2328 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
2331 if ( !empty($p_status) ) {
2332 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) ) {
2333 $statuswheres[] = "({$wpdb->posts}.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))";
2335 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
2338 if ( $post_status_join ) {
2339 $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) ";
2340 foreach ( $statuswheres as $index => $statuswhere ) {
2341 $statuswheres[$index] = "($statuswhere OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace( $wpdb->posts, 'p2', $statuswhere ) . "))";
2344 $where_status = implode( ' OR ', $statuswheres );
2345 if ( ! empty( $where_status ) ) {
2346 $where .= " AND ($where_status)";
2348 } elseif ( !$this->is_singular ) {
2349 $where .= " AND ({$wpdb->posts}.post_status = 'publish'";
2351 // Add public states.
2352 $public_states = get_post_stati( array('public' => true) );
2353 foreach ( (array) $public_states as $state ) {
2354 if ( 'publish' == $state ) // Publish is hard-coded above.
2356 $where .= " OR {$wpdb->posts}.post_status = '$state'";
2359 if ( $this->is_admin ) {
2360 // Add protected states that should show in the admin all list.
2361 $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) );
2362 foreach ( (array) $admin_all_states as $state ) {
2363 $where .= " OR {$wpdb->posts}.post_status = '$state'";
2367 if ( is_user_logged_in() ) {
2368 // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
2369 $private_states = get_post_stati( array('private' => true) );
2370 foreach ( (array) $private_states as $state ) {
2371 $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'";
2379 * Apply filters on where and join prior to paging so that any
2380 * manipulations to them are reflected in the paging by day queries.
2382 if ( !$q['suppress_filters'] ) {
2384 * Filters the WHERE clause of the query.
2388 * @param string $where The WHERE clause of the query.
2389 * @param WP_Query &$this The WP_Query instance (passed by reference).
2391 $where = apply_filters_ref_array( 'posts_where', array( $where, &$this ) );
2394 * Filters the JOIN clause of the query.
2398 * @param string $where The JOIN clause of the query.
2399 * @param WP_Query &$this The WP_Query instance (passed by reference).
2401 $join = apply_filters_ref_array( 'posts_join', array( $join, &$this ) );
2405 if ( empty($q['nopaging']) && !$this->is_singular ) {
2406 $page = absint($q['paged']);
2410 // If 'offset' is provided, it takes precedence over 'paged'.
2411 if ( isset( $q['offset'] ) && is_numeric( $q['offset'] ) ) {
2412 $q['offset'] = absint( $q['offset'] );
2413 $pgstrt = $q['offset'] . ', ';
2415 $pgstrt = absint( ( $page - 1 ) * $q['posts_per_page'] ) . ', ';
2417 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
2421 if ( $this->is_comment_feed && ! $this->is_singular ) {
2422 if ( $this->is_archive || $this->is_search ) {
2423 $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) $join ";
2424 $cwhere = "WHERE comment_approved = '1' $where";
2425 $cgroupby = "{$wpdb->comments}.comment_id";
2426 } else { // Other non singular e.g. front
2427 $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )";
2428 $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' AND post_type = 'attachment' ) ) AND comment_approved = '1'";
2432 if ( !$q['suppress_filters'] ) {
2434 * Filters the JOIN clause of the comments feed query before sending.
2438 * @param string $cjoin The JOIN clause of the query.
2439 * @param WP_Query &$this The WP_Query instance (passed by reference).
2441 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( $cjoin, &$this ) );
2444 * Filters the WHERE clause of the comments feed query before sending.
2448 * @param string $cwhere The WHERE clause of the query.
2449 * @param WP_Query &$this The WP_Query instance (passed by reference).
2451 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( $cwhere, &$this ) );
2454 * Filters the GROUP BY clause of the comments feed query before sending.
2458 * @param string $cgroupby The GROUP BY clause of the query.
2459 * @param WP_Query &$this The WP_Query instance (passed by reference).
2461 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( $cgroupby, &$this ) );
2464 * Filters the ORDER BY clause of the comments feed query before sending.
2468 * @param string $corderby The ORDER BY clause of the query.
2469 * @param WP_Query &$this The WP_Query instance (passed by reference).
2471 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
2474 * Filters the LIMIT clause of the comments feed query before sending.
2478 * @param string $climits The JOIN clause of the query.
2479 * @param WP_Query &$this The WP_Query instance (passed by reference).
2481 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
2483 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
2484 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
2486 $comments = (array) $wpdb->get_results("SELECT $distinct {$wpdb->comments}.* FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits");
2487 // Convert to WP_Comment
2488 $this->comments = array_map( 'get_comment', $comments );
2489 $this->comment_count = count($this->comments);
2491 $post_ids = array();
2493 foreach ( $this->comments as $comment )
2494 $post_ids[] = (int) $comment->comment_post_ID;
2496 $post_ids = join(',', $post_ids);
2499 $where = "AND {$wpdb->posts}.ID IN ($post_ids) ";
2505 $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' );
2508 * Apply post-paging filters on where and join. Only plugins that
2509 * manipulate paging queries should use these hooks.
2511 if ( !$q['suppress_filters'] ) {
2513 * Filters the WHERE clause of the query.
2515 * Specifically for manipulating paging queries.
2519 * @param string $where The WHERE clause of the query.
2520 * @param WP_Query &$this The WP_Query instance (passed by reference).
2522 $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) );
2525 * Filters the GROUP BY clause of the query.
2529 * @param string $groupby The GROUP BY clause of the query.
2530 * @param WP_Query &$this The WP_Query instance (passed by reference).
2532 $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) );
2535 * Filters the JOIN clause of the query.
2537 * Specifically for manipulating paging queries.
2541 * @param string $join The JOIN clause of the query.
2542 * @param WP_Query &$this The WP_Query instance (passed by reference).
2544 $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) );
2547 * Filters the ORDER BY clause of the query.
2551 * @param string $orderby The ORDER BY clause of the query.
2552 * @param WP_Query &$this The WP_Query instance (passed by reference).
2554 $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) );
2557 * Filters the DISTINCT clause of the query.
2561 * @param string $distinct The DISTINCT clause of the query.
2562 * @param WP_Query &$this The WP_Query instance (passed by reference).
2564 $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) );
2567 * Filters the LIMIT clause of the query.
2571 * @param string $limits The LIMIT clause of the query.
2572 * @param WP_Query &$this The WP_Query instance (passed by reference).
2574 $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) );
2577 * Filters the SELECT clause of the query.
2581 * @param string $fields The SELECT clause of the query.
2582 * @param WP_Query &$this The WP_Query instance (passed by reference).
2584 $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) );
2587 * Filters all query clauses at once, for convenience.
2589 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
2590 * fields (SELECT), and LIMITS clauses.
2594 * @param array $clauses The list of clauses for the query.
2595 * @param WP_Query &$this The WP_Query instance (passed by reference).
2597 $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) );
2599 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
2600 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
2601 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
2602 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
2603 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
2604 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
2605 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
2609 * Fires to announce the query's current selection parameters.
2611 * For use by caching plugins.
2615 * @param string $selection The assembled selection query.
2617 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
2620 * Filters again for the benefit of caching plugins.
2621 * Regular plugins should use the hooks above.
2623 if ( !$q['suppress_filters'] ) {
2625 * Filters the WHERE clause of the query.
2627 * For use by caching plugins.
2631 * @param string $where The WHERE clause of the query.
2632 * @param WP_Query &$this The WP_Query instance (passed by reference).
2634 $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) );
2637 * Filters the GROUP BY clause of the query.
2639 * For use by caching plugins.
2643 * @param string $groupby The GROUP BY clause of the query.
2644 * @param WP_Query &$this The WP_Query instance (passed by reference).
2646 $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) );
2649 * Filters the JOIN clause of the query.
2651 * For use by caching plugins.
2655 * @param string $join The JOIN clause of the query.
2656 * @param WP_Query &$this The WP_Query instance (passed by reference).
2658 $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) );
2661 * Filters the ORDER BY clause of the query.
2663 * For use by caching plugins.
2667 * @param string $orderby The ORDER BY clause of the query.
2668 * @param WP_Query &$this The WP_Query instance (passed by reference).
2670 $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) );
2673 * Filters the DISTINCT clause of the query.
2675 * For use by caching plugins.
2679 * @param string $distinct The DISTINCT clause of the query.
2680 * @param WP_Query &$this The WP_Query instance (passed by reference).
2682 $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) );
2685 * Filters the SELECT clause of the query.
2687 * For use by caching plugins.
2691 * @param string $fields The SELECT clause of the query.
2692 * @param WP_Query &$this The WP_Query instance (passed by reference).
2694 $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) );
2697 * Filters the LIMIT clause of the query.
2699 * For use by caching plugins.
2703 * @param string $limits The LIMIT clause of the query.
2704 * @param WP_Query &$this The WP_Query instance (passed by reference).
2706 $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) );
2709 * Filters all query clauses at once, for convenience.
2711 * For use by caching plugins.
2713 * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT,
2714 * fields (SELECT), and LIMITS clauses.
2718 * @param array $pieces The pieces of the query.
2719 * @param WP_Query &$this The WP_Query instance (passed by reference).
2721 $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) );
2723 $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
2724 $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
2725 $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
2726 $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
2727 $distinct = isset( $clauses[ 'distinct' ] ) ? $clauses[ 'distinct' ] : '';
2728 $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
2729 $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
2732 if ( ! empty($groupby) )
2733 $groupby = 'GROUP BY ' . $groupby;
2734 if ( !empty( $orderby ) )
2735 $orderby = 'ORDER BY ' . $orderby;
2738 if ( !$q['no_found_rows'] && !empty($limits) )
2739 $found_rows = 'SQL_CALC_FOUND_ROWS';
2741 $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM {$wpdb->posts} $join WHERE 1=1 $where $groupby $orderby $limits";
2743 if ( !$q['suppress_filters'] ) {
2745 * Filters the completed SQL query before sending.
2749 * @param string $request The complete SQL query.
2750 * @param WP_Query &$this The WP_Query instance (passed by reference).
2752 $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) );
2756 * Filters the posts array before the query takes place.
2758 * Return a non-null value to bypass WordPress's default post queries.
2760 * Filtering functions that require pagination information are encouraged to set
2761 * the `found_posts` and `max_num_pages` properties of the WP_Query object,
2762 * passed to the filter by reference. If WP_Query does not perform a database
2763 * query, it will not have enough information to generate these values itself.
2767 * @param array|null $posts Return an array of post data to short-circuit WP's query,
2768 * or null to allow WP to run its normal queries.
2769 * @param WP_Query $this The WP_Query instance, passed by reference.
2771 $this->posts = apply_filters_ref_array( 'posts_pre_query', array( null, &$this ) );
2773 if ( 'ids' == $q['fields'] ) {
2774 if ( null === $this->posts ) {
2775 $this->posts = $wpdb->get_col( $this->request );
2778 $this->posts = array_map( 'intval', $this->posts );
2779 $this->post_count = count( $this->posts );
2780 $this->set_found_posts( $q, $limits );
2782 return $this->posts;
2785 if ( 'id=>parent' == $q['fields'] ) {
2786 if ( null === $this->posts ) {
2787 $this->posts = $wpdb->get_results( $this->request );
2790 $this->post_count = count( $this->posts );
2791 $this->set_found_posts( $q, $limits );
2794 foreach ( $this->posts as $key => $post ) {
2795 $this->posts[ $key ]->ID = (int) $post->ID;
2796 $this->posts[ $key ]->post_parent = (int) $post->post_parent;
2798 $r[ (int) $post->ID ] = (int) $post->post_parent;
2804 if ( null === $this->posts ) {
2805 $split_the_query = ( $old_request == $this->request && "{$wpdb->posts}.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 );
2808 * Filters whether to split the query.
2810 * Splitting the query will cause it to fetch just the IDs of the found posts
2811 * (and then individually fetch each post by ID), rather than fetching every
2812 * complete row at once. One massive result vs. many small results.
2816 * @param bool $split_the_query Whether or not to split the query.
2817 * @param WP_Query $this The WP_Query instance.
2819 $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this );
2821 if ( $split_the_query ) {
2822 // First get the IDs and then fill in the objects
2824 $this->request = "SELECT $found_rows $distinct {$wpdb->posts}.ID FROM {$wpdb->posts} $join WHERE 1=1 $where $groupby $orderby $limits";
2827 * Filters the Post IDs SQL request before sending.
2831 * @param string $request The post ID request.
2832 * @param WP_Query $this The WP_Query instance.
2834 $this->request = apply_filters( 'posts_request_ids', $this->request, $this );
2836 $ids = $wpdb->get_col( $this->request );
2839 $this->posts = $ids;
2840 $this->set_found_posts( $q, $limits );
2841 _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] );
2843 $this->posts = array();
2846 $this->posts = $wpdb->get_results( $this->request );
2847 $this->set_found_posts( $q, $limits );
2851 // Convert to WP_Post objects.
2852 if ( $this->posts ) {
2853 $this->posts = array_map( 'get_post', $this->posts );
2856 if ( ! $q['suppress_filters'] ) {
2858 * Filters the raw post results array, prior to status checks.
2862 * @param array $posts The post results array.
2863 * @param WP_Query &$this The WP_Query instance (passed by reference).
2865 $this->posts = apply_filters_ref_array( 'posts_results', array( $this->posts, &$this ) );
2868 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
2869 /** This filter is documented in wp-includes/query.php */
2870 $cjoin = apply_filters_ref_array( 'comment_feed_join', array( '', &$this ) );
2872 /** This filter is documented in wp-includes/query.php */
2873 $cwhere = apply_filters_ref_array( 'comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) );
2875 /** This filter is documented in wp-includes/query.php */
2876 $cgroupby = apply_filters_ref_array( 'comment_feed_groupby', array( '', &$this ) );
2877 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
2879 /** This filter is documented in wp-includes/query.php */
2880 $corderby = apply_filters_ref_array( 'comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) );
2881 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
2883 /** This filter is documented in wp-includes/query.php */
2884 $climits = apply_filters_ref_array( 'comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) );
2886 $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} $cjoin $cwhere $cgroupby $corderby $climits";
2887 $comments = $wpdb->get_results($comments_request);
2888 // Convert to WP_Comment
2889 $this->comments = array_map( 'get_comment', $comments );
2890 $this->comment_count = count($this->comments);
2893 // Check post status to determine if post should be displayed.
2894 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
2895 $status = get_post_status($this->posts[0]);
2896 if ( 'attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent ) {
2897 $this->is_page = false;
2898 $this->is_single = true;
2899 $this->is_attachment = true;
2901 $post_status_obj = get_post_status_object($status);
2903 // If the post_status was specifically requested, let it pass through.
2904 if ( !$post_status_obj->public && ! in_array( $status, $q_status ) ) {
2906 if ( ! is_user_logged_in() ) {
2907 // User must be logged in to view unpublished posts.
2908 $this->posts = array();
2910 if ( $post_status_obj->protected ) {
2911 // User must have edit permissions on the draft to preview.
2912 if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) {
2913 $this->posts = array();
2915 $this->is_preview = true;
2916 if ( 'future' != $status )
2917 $this->posts[0]->post_date = current_time('mysql');
2919 } elseif ( $post_status_obj->private ) {
2920 if ( ! current_user_can($read_cap, $this->posts[0]->ID) )
2921 $this->posts = array();
2923 $this->posts = array();
2928 if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) {
2930 * Filters the single post for preview mode.
2934 * @param WP_Post $post_preview The Post object.
2935 * @param WP_Query &$this The WP_Query instance (passed by reference).
2937 $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) );
2941 // Put sticky posts at the top of the posts array
2942 $sticky_posts = get_option('sticky_posts');
2943 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) {
2944 $num_posts = count($this->posts);
2946 // Loop over posts and relocate stickies to the front.
2947 for ( $i = 0; $i < $num_posts; $i++ ) {
2948 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
2949 $sticky_post = $this->posts[$i];
2950 // Remove sticky from current position
2951 array_splice($this->posts, $i, 1);
2952 // Move to front, after other stickies
2953 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
2954 // Increment the sticky offset. The next sticky will be placed at this offset.
2956 // Remove post from sticky posts array
2957 $offset = array_search($sticky_post->ID, $sticky_posts);
2958 unset( $sticky_posts[$offset] );
2962 // If any posts have been excluded specifically, Ignore those that are sticky.
2963 if ( !empty($sticky_posts) && !empty($q['post__not_in']) )
2964 $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
2966 // Fetch sticky posts that weren't in the query results
2967 if ( !empty($sticky_posts) ) {
2968 $stickies = get_posts( array(
2969 'post__in' => $sticky_posts,
2970 'post_type' => $post_type,
2971 'post_status' => 'publish',
2975 foreach ( $stickies as $sticky_post ) {
2976 array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) );
2982 // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up.
2983 if ( ! empty( $this->comments ) ) {
2984 wp_queue_comments_for_comment_meta_lazyload( $this->comments );
2987 if ( ! $q['suppress_filters'] ) {
2989 * Filters the array of retrieved posts after they've been fetched and
2990 * internally processed.
2994 * @param array $posts The array of retrieved posts.
2995 * @param WP_Query &$this The WP_Query instance (passed by reference).
2997 $this->posts = apply_filters_ref_array( 'the_posts', array( $this->posts, &$this ) );
3000 // Ensure that any posts added/modified via one of the filters above are
3001 // of the type WP_Post and are filtered.
3002 if ( $this->posts ) {
3003 $this->post_count = count( $this->posts );
3005 $this->posts = array_map( 'get_post', $this->posts );
3007 if ( $q['cache_results'] )
3008 update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
3010 $this->post = reset( $this->posts );
3012 $this->post_count = 0;
3013 $this->posts = array();
3016 if ( $q['lazy_load_term_meta'] ) {
3017 wp_queue_posts_for_term_meta_lazyload( $this->posts );
3020 return $this->posts;
3024 * Set up the amount of found posts and the number of pages (if limit clause was used)
3025 * for the current query.
3030 * @param array $q Query variables.
3031 * @param string $limits LIMIT clauses of the query.
3033 private function set_found_posts( $q, $limits ) {
3035 // Bail if posts is an empty array. Continue if posts is an empty string,
3036 // null, or false to accommodate caching plugins that fill posts later.
3037 if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) )
3040 if ( ! empty( $limits ) ) {
3042 * Filters the query to run for retrieving the found posts.
3046 * @param string $found_posts The query to run to find the found posts.
3047 * @param WP_Query &$this The WP_Query instance (passed by reference).
3049 $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) );
3051 $this->found_posts = count( $this->posts );
3055 * Filters the number of found posts for the query.
3059 * @param int $found_posts The number of posts found.
3060 * @param WP_Query &$this The WP_Query instance (passed by reference).
3062 $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) );
3064 if ( ! empty( $limits ) )
3065 $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] );
3069 * Set up the next post and iterate current post index.
3074 * @return WP_Post Next post.
3076 public function next_post() {
3078 $this->current_post++;
3080 $this->post = $this->posts[$this->current_post];
3085 * Sets up the current post.
3087 * Retrieves the next post, sets up the post, sets the 'in the loop'
3093 * @global WP_Post $post
3095 public function the_post() {
3097 $this->in_the_loop = true;
3099 if ( $this->current_post == -1 ) // loop has just started
3101 * Fires once the loop is started.
3105 * @param WP_Query &$this The WP_Query instance (passed by reference).
3107 do_action_ref_array( 'loop_start', array( &$this ) );
3109 $post = $this->next_post();
3110 $this->setup_postdata( $post );
3114 * Determines whether there are more posts available in the loop.
3116 * Calls the {@see 'loop_end'} action when the loop is complete.
3121 * @return bool True if posts are available, false if end of loop.
3123 public function have_posts() {
3124 if ( $this->current_post + 1 < $this->post_count ) {
3126 } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) {
3128 * Fires once the loop has ended.
3132 * @param WP_Query &$this The WP_Query instance (passed by reference).
3134 do_action_ref_array( 'loop_end', array( &$this ) );
3135 // Do some cleaning up after the loop
3136 $this->rewind_posts();
3139 $this->in_the_loop = false;
3144 * Rewind the posts and reset post index.
3149 public function rewind_posts() {
3150 $this->current_post = -1;
3151 if ( $this->post_count > 0 ) {
3152 $this->post = $this->posts[0];
3157 * Iterate current comment index and return WP_Comment object.
3162 * @return WP_Comment Comment object.
3164 public function next_comment() {
3165 $this->current_comment++;
3167 $this->comment = $this->comments[$this->current_comment];
3168 return $this->comment;
3172 * Sets up the current comment.
3176 * @global WP_Comment $comment Current comment.
3178 public function the_comment() {
3181 $comment = $this->next_comment();
3183 if ( $this->current_comment == 0 ) {
3185 * Fires once the comment loop is started.
3189 do_action( 'comment_loop_start' );
3194 * Whether there are more comments available.
3196 * Automatically rewinds comments when finished.
3201 * @return bool True, if more comments. False, if no more posts.
3203 public function have_comments() {
3204 if ( $this->current_comment + 1 < $this->comment_count ) {
3206 } elseif ( $this->current_comment + 1 == $this->comment_count ) {
3207 $this->rewind_comments();
3214 * Rewind the comments, resets the comment index and comment to first.
3219 public function rewind_comments() {
3220 $this->current_comment = -1;
3221 if ( $this->comment_count > 0 ) {
3222 $this->comment = $this->comments[0];
3227 * Sets up the WordPress query by parsing query string.
3232 * @param string $query URL query string.
3233 * @return array List of posts.
3235 public function query( $query ) {
3237 $this->query = $this->query_vars = wp_parse_args( $query );
3238 return $this->get_posts();
3242 * Retrieve queried object.
3244 * If queried object is not set, then the queried object will be set from
3245 * the category, tag, taxonomy, posts page, single post, page, or author
3246 * query variable. After it is set up, it will be returned.
3253 public function get_queried_object() {
3254 if ( isset($this->queried_object) )
3255 return $this->queried_object;
3257 $this->queried_object = null;
3258 $this->queried_object_id = null;
3260 if ( $this->is_category || $this->is_tag || $this->is_tax ) {
3261 if ( $this->is_category ) {
3262 if ( $this->get( 'cat' ) ) {
3263 $term = get_term( $this->get( 'cat' ), 'category' );
3264 } elseif ( $this->get( 'category_name' ) ) {
3265 $term = get_term_by( 'slug', $this->get( 'category_name' ), 'category' );
3267 } elseif ( $this->is_tag ) {
3268 if ( $this->get( 'tag_id' ) ) {
3269 $term = get_term( $this->get( 'tag_id' ), 'post_tag' );
3270 } elseif ( $this->get( 'tag' ) ) {
3271 $term = get_term_by( 'slug', $this->get( 'tag' ), 'post_tag' );
3274 // For other tax queries, grab the first term from the first clause.
3275 if ( ! empty( $this->tax_query->queried_terms ) ) {
3276 $queried_taxonomies = array_keys( $this->tax_query->queried_terms );
3277 $matched_taxonomy = reset( $queried_taxonomies );
3278 $query = $this->tax_query->queried_terms[ $matched_taxonomy ];
3280 if ( ! empty( $query['terms'] ) ) {
3281 if ( 'term_id' == $query['field'] ) {
3282 $term = get_term( reset( $query['terms'] ), $matched_taxonomy );
3284 $term = get_term_by( $query['field'], reset( $query['terms'] ), $matched_taxonomy );
3290 if ( ! empty( $term ) && ! is_wp_error( $term ) ) {
3291 $this->queried_object = $term;
3292 $this->queried_object_id = (int) $term->term_id;
3294 if ( $this->is_category && 'category' === $this->queried_object->taxonomy )
3295 _make_cat_compat( $this->queried_object );
3297 } elseif ( $this->is_post_type_archive ) {
3298 $post_type = $this->get( 'post_type' );
3299 if ( is_array( $post_type ) )
3300 $post_type = reset( $post_type );
3301 $this->queried_object = get_post_type_object( $post_type );
3302 } elseif ( $this->is_posts_page ) {
3303 $page_for_posts = get_option('page_for_posts');
3304 $this->queried_object = get_post( $page_for_posts );
3305 $this->queried_object_id = (int) $this->queried_object->ID;
3306 } elseif ( $this->is_singular && ! empty( $this->post ) ) {
3307 $this->queried_object = $this->post;
3308 $this->queried_object_id = (int) $this->post->ID;
3309 } elseif ( $this->is_author ) {
3310 $this->queried_object_id = (int) $this->get('author');
3311 $this->queried_object = get_userdata( $this->queried_object_id );
3314 return $this->queried_object;
3318 * Retrieve ID of the current queried object.
3325 public function get_queried_object_id() {
3326 $this->get_queried_object();
3328 if ( isset($this->queried_object_id) ) {
3329 return $this->queried_object_id;
3338 * Sets up the WordPress query, if parameter is not empty.
3343 * @param string|array $query URL query string or array of vars.
3345 public function __construct( $query = '' ) {
3346 if ( ! empty( $query ) ) {
3347 $this->query( $query );
3352 * Make private properties readable for backward compatibility.
3357 * @param string $name Property to get.
3358 * @return mixed Property.
3360 public function __get( $name ) {
3361 if ( in_array( $name, $this->compat_fields ) ) {
3362 return $this->$name;
3367 * Make private properties checkable for backward compatibility.
3372 * @param string $name Property to check if set.
3373 * @return bool Whether the property is set.
3375 public function __isset( $name ) {
3376 if ( in_array( $name, $this->compat_fields ) ) {
3377 return isset( $this->$name );
3382 * Make private/protected methods readable for backward compatibility.
3387 * @param callable $name Method to call.
3388 * @param array $arguments Arguments to pass when calling.
3389 * @return mixed|false Return value of the callback, false otherwise.
3391 public function __call( $name, $arguments ) {
3392 if ( in_array( $name, $this->compat_methods ) ) {
3393 return call_user_func_array( array( $this, $name ), $arguments );
3399 * Is the query for an existing archive page?
3401 * Month, Year, Category, Author, Post Type archive...
3407 public function is_archive() {
3408 return (bool) $this->is_archive;
3412 * Is the query for an existing post type archive page?
3416 * @param mixed $post_types Optional. Post type or array of posts types to check against.
3419 public function is_post_type_archive( $post_types = '' ) {
3420 if ( empty( $post_types ) || ! $this->is_post_type_archive )
3421 return (bool) $this->is_post_type_archive;
3423 $post_type = $this->get( 'post_type' );
3424 if ( is_array( $post_type ) )
3425 $post_type = reset( $post_type );
3426 $post_type_object = get_post_type_object( $post_type );
3428 return in_array( $post_type_object->name, (array) $post_types );
3432 * Is the query for an existing attachment page?
3436 * @param mixed $attachment Attachment ID, title, slug, or array of such.
3439 public function is_attachment( $attachment = '' ) {
3440 if ( ! $this->is_attachment ) {
3444 if ( empty( $attachment ) ) {
3448 $attachment = array_map( 'strval', (array) $attachment );
3450 $post_obj = $this->get_queried_object();
3452 if ( in_array( (string) $post_obj->ID, $attachment ) ) {
3454 } elseif ( in_array( $post_obj->post_title, $attachment ) ) {
3456 } elseif ( in_array( $post_obj->post_name, $attachment ) ) {
3463 * Is the query for an existing author archive page?
3465 * If the $author parameter is specified, this function will additionally
3466 * check if the query is for one of the authors specified.
3470 * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames
3473 public function is_author( $author = '' ) {
3474 if ( !$this->is_author )
3477 if ( empty($author) )
3480 $author_obj = $this->get_queried_object();
3482 $author = array_map( 'strval', (array) $author );
3484 if ( in_array( (string) $author_obj->ID, $author ) )
3486 elseif ( in_array( $author_obj->nickname, $author ) )
3488 elseif ( in_array( $author_obj->user_nicename, $author ) )
3495 * Is the query for an existing category archive page?
3497 * If the $category parameter is specified, this function will additionally
3498 * check if the query is for one of the categories specified.
3502 * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs.
3505 public function is_category( $category = '' ) {
3506 if ( !$this->is_category )
3509 if ( empty($category) )
3512 $cat_obj = $this->get_queried_object();
3514 $category = array_map( 'strval', (array) $category );
3516 if ( in_array( (string) $cat_obj->term_id, $category ) )
3518 elseif ( in_array( $cat_obj->name, $category ) )
3520 elseif ( in_array( $cat_obj->slug, $category ) )
3527 * Is the query for an existing tag archive page?
3529 * If the $tag parameter is specified, this function will additionally
3530 * check if the query is for one of the tags specified.
3534 * @param mixed $tag Optional. Tag ID, name, slug, or array of Tag IDs, names, and slugs.
3537 public function is_tag( $tag = '' ) {
3538 if ( ! $this->is_tag )
3541 if ( empty( $tag ) )
3544 $tag_obj = $this->get_queried_object();
3546 $tag = array_map( 'strval', (array) $tag );
3548 if ( in_array( (string) $tag_obj->term_id, $tag ) )
3550 elseif ( in_array( $tag_obj->name, $tag ) )
3552 elseif ( in_array( $tag_obj->slug, $tag ) )
3559 * Is the query for an existing custom taxonomy archive page?
3561 * If the $taxonomy parameter is specified, this function will additionally
3562 * check if the query is for that specific $taxonomy.
3564 * If the $term parameter is specified in addition to the $taxonomy parameter,
3565 * this function will additionally check if the query is for one of the terms
3570 * @global array $wp_taxonomies
3572 * @param mixed $taxonomy Optional. Taxonomy slug or slugs.
3573 * @param mixed $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs.
3574 * @return bool True for custom taxonomy archive pages, false for built-in taxonomies (category and tag archives).
3576 public function is_tax( $taxonomy = '', $term = '' ) {
3577 global $wp_taxonomies;
3579 if ( !$this->is_tax )
3582 if ( empty( $taxonomy ) )
3585 $queried_object = $this->get_queried_object();
3586 $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy );
3587 $term_array = (array) $term;
3589 // Check that the taxonomy matches.
3590 if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) )
3593 // Only a Taxonomy provided.
3594 if ( empty( $term ) )
3597 return isset( $queried_object->term_id ) &&
3598 count( array_intersect(
3599 array( $queried_object->term_id, $queried_object->name, $queried_object->slug ),
3605 * Whether the current URL is within the comments popup window.
3612 public function is_comments_popup() {
3613 _deprecated_function( __FUNCTION__, '4.5.0' );
3619 * Is the query for an existing date archive?
3625 public function is_date() {
3626 return (bool) $this->is_date;
3630 * Is the query for an existing day archive?
3636 public function is_day() {
3637 return (bool) $this->is_day;
3641 * Is the query for a feed?
3645 * @param string|array $feeds Optional feed types to check.
3648 public function is_feed( $feeds = '' ) {
3649 if ( empty( $feeds ) || ! $this->is_feed )
3650 return (bool) $this->is_feed;
3651 $qv = $this->get( 'feed' );
3652 if ( 'feed' == $qv )
3653 $qv = get_default_feed();
3654 return in_array( $qv, (array) $feeds );
3658 * Is the query for a comments feed?
3664 public function is_comment_feed() {
3665 return (bool) $this->is_comment_feed;
3669 * Is the query for the front page of the site?
3671 * This is for what is displayed at your site's main URL.
3673 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'.
3675 * If you set a static page for the front page of your site, this function will return
3676 * true when viewing that page.
3678 * Otherwise the same as @see WP_Query::is_home()
3682 * @return bool True, if front of site.
3684 public function is_front_page() {
3686 if ( 'posts' == get_option( 'show_on_front') && $this->is_home() )
3688 elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) )
3695 * Is the query for the blog homepage?
3697 * This is the page which shows the time based blog content of your site.
3699 * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'.
3701 * If you set a static page for the front page of your site, this function will return
3702 * true only on the page you set as the "Posts page".
3704 * @see WP_Query::is_front_page()
3708 * @return bool True if blog view homepage.
3710 public function is_home() {
3711 return (bool) $this->is_home;
3715 * Is the query for an existing month archive?
3721 public function is_month() {
3722 return (bool) $this->is_month;
3726 * Is the query for an existing single page?
3728 * If the $page parameter is specified, this function will additionally
3729 * check if the query is for one of the pages specified.
3731 * @see WP_Query::is_single()
3732 * @see WP_Query::is_singular()
3736 * @param int|string|array $page Optional. Page ID, title, slug, path, or array of such. Default empty.
3737 * @return bool Whether the query is for an existing single page.
3739 public function is_page( $page = '' ) {
3740 if ( !$this->is_page )
3743 if ( empty( $page ) )
3746 $page_obj = $this->get_queried_object();
3748 $page = array_map( 'strval', (array) $page );
3750 if ( in_array( (string) $page_obj->ID, $page ) ) {
3752 } elseif ( in_array( $page_obj->post_title, $page ) ) {
3754 } elseif ( in_array( $page_obj->post_name, $page ) ) {
3757 foreach ( $page as $pagepath ) {
3758 if ( ! strpos( $pagepath, '/' ) ) {
3761 $pagepath_obj = get_page_by_path( $pagepath );
3763 if ( $pagepath_obj && ( $pagepath_obj->ID == $page_obj->ID ) ) {
3773 * Is the query for paged result and not for the first page?
3779 public function is_paged() {
3780 return (bool) $this->is_paged;
3784 * Is the query for a post or page preview?
3790 public function is_preview() {
3791 return (bool) $this->is_preview;
3795 * Is the query for the robots file?
3801 public function is_robots() {
3802 return (bool) $this->is_robots;
3806 * Is the query for a search?
3812 public function is_search() {
3813 return (bool) $this->is_search;
3817 * Is the query for an existing single post?
3819 * Works for any post type excluding pages.
3821 * If the $post parameter is specified, this function will additionally
3822 * check if the query is for one of the Posts specified.
3824 * @see WP_Query::is_page()
3825 * @see WP_Query::is_singular()
3829 * @param int|string|array $post Optional. Post ID, title, slug, path, or array of such. Default empty.
3830 * @return bool Whether the query is for an existing single post.
3832 public function is_single( $post = '' ) {
3833 if ( !$this->is_single )
3839 $post_obj = $this->get_queried_object();
3841 $post = array_map( 'strval', (array) $post );
3843 if ( in_array( (string) $post_obj->ID, $post ) ) {
3845 } elseif ( in_array( $post_obj->post_title, $post ) ) {
3847 } elseif ( in_array( $post_obj->post_name, $post ) ) {
3850 foreach ( $post as $postpath ) {
3851 if ( ! strpos( $postpath, '/' ) ) {
3854 $postpath_obj = get_page_by_path( $postpath, OBJECT, $post_obj->post_type );
3856 if ( $postpath_obj && ( $postpath_obj->ID == $post_obj->ID ) ) {
3865 * Is the query for an existing single post of any post type (post, attachment, page, ... )?
3867 * If the $post_types parameter is specified, this function will additionally
3868 * check if the query is for one of the Posts Types specified.
3870 * @see WP_Query::is_page()
3871 * @see WP_Query::is_single()
3875 * @param string|array $post_types Optional. Post type or array of post types. Default empty.
3876 * @return bool Whether the query is for an existing single post of any of the given post types.
3878 public function is_singular( $post_types = '' ) {
3879 if ( empty( $post_types ) || !$this->is_singular )
3880 return (bool) $this->is_singular;
3882 $post_obj = $this->get_queried_object();
3884 return in_array( $post_obj->post_type, (array) $post_types );
3888 * Is the query for a specific time?
3894 public function is_time() {
3895 return (bool) $this->is_time;
3899 * Is the query for a trackback endpoint call?
3905 public function is_trackback() {
3906 return (bool) $this->is_trackback;
3910 * Is the query for an existing year archive?
3916 public function is_year() {
3917 return (bool) $this->is_year;
3921 * Is the query a 404 (returns no results)?
3927 public function is_404() {
3928 return (bool) $this->is_404;
3932 * Is the query for an embedded post?
3938 public function is_embed() {
3939 return (bool) $this->is_embed;
3943 * Is the query the main query?
3947 * @global WP_Query $wp_query Global WP_Query instance.
3951 public function is_main_query() {
3952 global $wp_the_query;
3953 return $wp_the_query === $this;
3957 * Set up global post data.
3960 * @since 4.4.0 Added the ability to pass a post ID to `$post`.
3963 * @global WP_User $authordata
3964 * @global string|int|bool $currentday
3965 * @global string|int|bool $currentmonth
3967 * @global array $pages
3968 * @global int $multipage
3970 * @global int $numpages
3972 * @param WP_Post|object|int $post WP_Post instance or Post ID/object.
3973 * @return true True when finished.
3975 public function setup_postdata( $post ) {
3976 global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages;
3978 if ( ! ( $post instanceof WP_Post ) ) {
3979 $post = get_post( $post );
3986 $id = (int) $post->ID;
3988 $authordata = get_userdata($post->post_author);
3990 $currentday = mysql2date('d.m.y', $post->post_date, false);
3991 $currentmonth = mysql2date('m', $post->post_date, false);
3994 $page = $this->get( 'page' );
3999 * Force full post content when viewing the permalink for the $post,
4000 * or when on an RSS feed. Otherwise respect the 'more' tag.
4002 if ( $post->ID === get_queried_object_id() && ( $this->is_page() || $this->is_single() ) ) {
4004 } elseif ( $this->is_feed() ) {
4010 $content = $post->post_content;
4011 if ( false !== strpos( $content, '<!--nextpage-->' ) ) {
4012 $content = str_replace( "\n<!--nextpage-->\n", '<!--nextpage-->', $content );
4013 $content = str_replace( "\n<!--nextpage-->", '<!--nextpage-->', $content );
4014 $content = str_replace( "<!--nextpage-->\n", '<!--nextpage-->', $content );
4016 // Ignore nextpage at the beginning of the content.
4017 if ( 0 === strpos( $content, '<!--nextpage-->' ) )
4018 $content = substr( $content, 15 );
4020 $pages = explode('<!--nextpage-->', $content);
4022 $pages = array( $post->post_content );
4026 * Filters the "pages" derived from splitting the post content.
4028 * "Pages" are determined by splitting the post content based on the presence
4029 * of `<!-- nextpage -->` tags.
4033 * @param array $pages Array of "pages" derived from the post content.
4034 * of `<!-- nextpage -->` tags..
4035 * @param WP_Post $post Current post object.
4037 $pages = apply_filters( 'content_pagination', $pages, $post );
4039 $numpages = count( $pages );
4041 if ( $numpages > 1 ) {
4051 * Fires once the post data has been setup.
4054 * @since 4.1.0 Introduced `$this` parameter.
4056 * @param WP_Post &$post The Post object (passed by reference).
4057 * @param WP_Query &$this The current Query object (passed by reference).
4059 do_action_ref_array( 'the_post', array( &$post, &$this ) );
4064 * After looping through a nested query, this function
4065 * restores the $post global to the current post in this query.
4069 * @global WP_Post $post
4071 public function reset_postdata() {
4072 if ( ! empty( $this->post ) ) {
4073 $GLOBALS['post'] = $this->post;
4074 $this->setup_postdata( $this->post );
4079 * Lazyload term meta for posts in the loop.
4082 * @deprecated 4.5.0 See wp_queue_posts_for_term_meta_lazyload().
4084 * @param mixed $check
4085 * @param int $term_id
4088 public function lazyload_term_meta( $check, $term_id ) {
4089 _deprecated_function( __METHOD__, '4.5.0' );
4094 * Lazyload comment meta for comments in the loop.
4097 * @deprecated 4.5.0 See wp_queue_comments_for_comment_meta_lazyload().
4099 * @param mixed $check
4100 * @param int $comment_id
4103 public function lazyload_comment_meta( $check, $comment_id ) {
4104 _deprecated_function( __METHOD__, '4.5.0' );