5 * The query API attempts to get which part of WordPress to the user is on. It
6 * also provides functionality to getting URL query information.
8 * @link http://codex.wordpress.org/The_Loop More information on The Loop.
15 * Retrieve variable in the WP_Query class.
17 * @see WP_Query::get()
21 * @param string $var The variable key to retrieve.
24 function get_query_var($var) {
27 return $wp_query->get($var);
33 * @see WP_Query::set()
37 * @param string $var Query variable key.
41 function set_query_var($var, $value) {
44 return $wp_query->set($var, $value);
48 * Setup The Loop with query parameters.
50 * This will override the current WordPress Loop and shouldn't be used more than
51 * once. This must not be used within the WordPress Loop.
56 * @param string $query
57 * @return array List of posts
59 function &query_posts($query) {
60 unset($GLOBALS['wp_query']);
61 $GLOBALS['wp_query'] =& new WP_Query();
62 return $GLOBALS['wp_query']->query($query);
66 * Destroy the previous query and setup a new query.
68 * This should be used after {@link query_posts()} and before another {@link
69 * query_posts()}. This will remove obscure bugs that occur when the previous
70 * wp_query object is not destroyed properly before another is setup.
75 function wp_reset_query() {
76 unset($GLOBALS['wp_query']);
77 $GLOBALS['wp_query'] =& $GLOBALS['wp_the_query'];
79 if ( !empty($wp_query->post) ) {
80 $GLOBALS['post'] = $wp_query->post;
81 setup_postdata($wp_query->post);
90 * Whether the current request is in WordPress admin Panel
92 * Does not inform on whether the user is an admin! Use capability checks to
93 * tell if the user should be accessing a section or not.
97 * @return bool True if inside WordPress administration pages.
99 function is_admin () {
100 if ( defined('WP_ADMIN') )
106 * Is query requesting an archive page.
111 * @return bool True if page is archive.
113 function is_archive () {
116 return $wp_query->is_archive;
120 * Is query requesting an attachment page.
125 * @return bool True if page is attachment.
127 function is_attachment () {
130 return $wp_query->is_attachment;
134 * Is query requesting an author page.
136 * If the $author parameter is specified then the check will be expanded to
137 * include whether the queried author matches the one given in the parameter.
138 * You can match against integers and against strings.
140 * If matching against an integer, the ID should be used of the author for the
141 * test. If the $author is an ID and matches the author page user ID, then
142 * 'true' will be returned.
144 * If matching against strings, then the test will be matched against both the
145 * nickname and user nicename and will return true on success.
150 * @param string|int $author Optional. Is current page this author.
151 * @return bool True if page is author or $author (if set).
153 function is_author ($author = '') {
156 if ( !$wp_query->is_author )
159 if ( empty($author) )
162 $author_obj = $wp_query->get_queried_object();
164 $author = (array) $author;
166 if ( in_array( $author_obj->ID, $author ) )
168 elseif ( in_array( $author_obj->nickname, $author ) )
170 elseif ( in_array( $author_obj->user_nicename, $author ) )
177 * Whether current page query contains a category name or given category name.
179 * The category list can contain category IDs, names, or category slugs. If any
180 * of them are part of the query, then it will return true.
185 * @param string|array $category Optional.
188 function is_category ($category = '') {
191 if ( !$wp_query->is_category )
194 if ( empty($category) )
197 $cat_obj = $wp_query->get_queried_object();
199 $category = (array) $category;
201 if ( in_array( $cat_obj->term_id, $category ) )
203 elseif ( in_array( $cat_obj->name, $category ) )
205 elseif ( in_array( $cat_obj->slug, $category ) )
212 * Whether the current page query has the given tag slug or contains tag.
217 * @param string|array $slug Optional. Single tag or list of tags to check for.
220 function is_tag( $slug = '' ) {
223 if ( !$wp_query->is_tag )
226 if ( empty( $slug ) )
229 $tag_obj = $wp_query->get_queried_object();
231 $slug = (array) $slug;
233 if ( in_array( $tag_obj->slug, $slug ) )
240 * Whether the current page query has the given taxonomy slug or contains taxonomy.
245 * @param string|array $slug Optional. Slug or slugs to check in current query.
248 function is_tax( $slug = '' ) {
251 if ( !$wp_query->is_tax )
257 $term = $wp_query->get_queried_object();
259 $slug = (array) $slug;
261 if ( in_array( $term->slug, $slug ) )
268 * Whether the current URL is within the comments popup window.
275 function is_comments_popup () {
278 return $wp_query->is_comments_popup;
282 * Whether current URL is based on a date.
289 function is_date () {
292 return $wp_query->is_date;
296 * Whether current blog URL contains a day.
306 return $wp_query->is_day;
310 * Whether current page query is feed URL.
317 function is_feed () {
320 return $wp_query->is_feed;
324 * Whether current page query is the front of the site.
330 * @return bool True, if front of site.
332 function is_front_page () {
334 if ( 'posts' == get_option('show_on_front') && is_home() )
336 elseif ( 'page' == get_option('show_on_front') && get_option('page_on_front') && is_page(get_option('page_on_front')) )
343 * Whether current page view is the blog homepage.
348 * @return bool True if blog view homepage.
350 function is_home () {
353 return $wp_query->is_home;
357 * Whether current page query contains a month.
364 function is_month () {
367 return $wp_query->is_month;
371 * Whether query is page or contains given page(s).
373 * Calls the function without any parameters will only test whether the current
374 * query is of the page type. Either a list or a single item can be tested
375 * against for whether the query is a page and also is the value or one of the
376 * values in the page parameter.
378 * The parameter can contain the page ID, page title, or page name. The
379 * parameter can also be an array of those three values.
384 * @param mixed $page Either page or list of pages to test against.
387 function is_page ($page = '') {
390 if ( !$wp_query->is_page )
396 $page_obj = $wp_query->get_queried_object();
398 $page = (array) $page;
400 if ( in_array( $page_obj->ID, $page ) )
402 elseif ( in_array( $page_obj->post_title, $page ) )
404 else if ( in_array( $page_obj->post_name, $page ) )
411 * Whether query contains multiple pages for the results.
418 function is_paged () {
421 return $wp_query->is_paged;
425 * Whether the current page was created by a plugin.
427 * The plugin can set this by using the global $plugin_page and setting it to
431 * @global bool $plugin_page Used by plugins to tell the query that current is a plugin page.
435 function is_plugin_page() {
438 if ( isset($plugin_page) )
445 * Whether the current query is preview of post or page.
452 function is_preview() {
455 return $wp_query->is_preview;
459 * Whether the current query post is robots.
466 function is_robots() {
469 return $wp_query->is_robots;
473 * Whether current query is the result of a user search.
480 function is_search () {
483 return $wp_query->is_search;
487 * Whether the current page query is single page.
489 * The parameter can contain the post ID, post title, or post name. The
490 * parameter can also be an array of those three values.
492 * This applies to other post types, attachments, pages, posts. Just means that
493 * the current query has only a single object.
498 * @param mixed $post Either post or list of posts to test against.
501 function is_single ($post = '') {
504 if ( !$wp_query->is_single )
510 $post_obj = $wp_query->get_queried_object();
512 $post = (array) $post;
514 if ( in_array( $post_obj->ID, $post ) )
516 elseif ( in_array( $post_obj->post_title, $post ) )
518 elseif ( in_array( $post_obj->post_name, $post ) )
525 * Whether is single post, is a page, or is an attachment.
532 function is_singular() {
535 return $wp_query->is_singular;
539 * Whether the query contains a time.
546 function is_time () {
549 return $wp_query->is_time;
553 * Whether the query is a trackback.
560 function is_trackback () {
563 return $wp_query->is_trackback;
567 * Whether the query contains a year.
574 function is_year () {
577 return $wp_query->is_year;
581 * Whether current page query is a 404 and no results for WordPress query.
586 * @return bool True, if nothing is found matching WordPress Query.
591 return $wp_query->is_404;
595 * The Loop. Post loop control.
599 * Whether current WordPress query has results to loop over.
601 * @see WP_Query::have_posts()
607 function have_posts() {
610 return $wp_query->have_posts();
614 * Whether the caller is in the Loop.
619 * @return bool True if caller is within loop, false if loop hasn't started or ended.
621 function in_the_loop() {
624 return $wp_query->in_the_loop;
628 * Rewind the loop posts.
630 * @see WP_Query::rewind_posts()
636 function rewind_posts() {
639 return $wp_query->rewind_posts();
643 * Iterate the post index in the loop.
645 * @see WP_Query::the_post()
649 function the_post() {
652 $wp_query->the_post();
660 * Whether there are comments to loop over.
662 * @see WP_Query::have_comments()
668 function have_comments() {
670 return $wp_query->have_comments();
674 * Iterate comment index in the comment loop.
676 * @see WP_Query::the_comment()
682 function the_comment() {
684 return $wp_query->the_comment();
692 * The WordPress Query class.
694 * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page.
710 * Query search variables set by the user.
716 var $query_vars = array();
719 * Holds the data for a single object that is queried.
721 * Holds the contents of a post, page, category, attachment.
730 * The ID of the queried object.
736 var $queried_object_id;
739 * Get post database query.
757 * The amount of posts for the current query.
766 * Index of the current item in the loop.
772 var $current_post = -1;
775 * Whether the loop has started and the caller is in the loop.
781 var $in_the_loop = false;
784 * The current post ID.
793 * The list of comments for current post.
802 * The amount of comments for the posts.
808 var $comment_count = 0;
811 * The index of the comment in the comment loop.
817 var $current_comment = -1;
820 * Current comment ID.
829 * Amount of posts if limit clause was not used.
835 var $found_posts = 0;
838 * The amount of pages.
844 var $max_num_pages = 0;
847 * The amount of comment pages.
853 var $max_num_comment_pages = 0;
856 * Set if query is single post.
862 var $is_single = false;
865 * Set if query is preview of blog.
871 var $is_preview = false;
874 * Set if query returns a page.
880 var $is_page = false;
883 * Set if query is an archive list.
889 var $is_archive = false;
892 * Set if query is part of a date.
898 var $is_date = false;
901 * Set if query contains a year.
907 var $is_year = false;
910 * Set if query contains a month.
916 var $is_month = false;
919 * Set if query contains a day.
928 * Set if query contains time.
934 var $is_time = false;
937 * Set if query contains an author.
943 var $is_author = false;
946 * Set if query contains category.
952 var $is_category = false;
955 * Set if query contains tag.
964 * Set if query contains taxonomy.
973 * Set if query was part of a search result.
979 var $is_search = false;
982 * Set if query is feed display.
988 var $is_feed = false;
991 * Set if query is comment feed display.
997 var $is_comment_feed = false;
1000 * Set if query is trackback.
1006 var $is_trackback = false;
1009 * Set if query is blog homepage.
1015 var $is_home = false;
1018 * Set if query couldn't found anything.
1024 var $is_404 = false;
1027 * Set if query is within comments popup window.
1033 var $is_comments_popup = false;
1036 * Set if query is part of administration page.
1042 var $is_admin = false;
1045 * Set if query is an attachment.
1051 var $is_attachment = false;
1054 * Set if is single, is a page, or is an attachment.
1060 var $is_singular = false;
1063 * Set if query is for robots.
1069 var $is_robots = false;
1072 * Set if query contains posts.
1074 * Basically, the homepage if the option isn't set for the static homepage.
1080 var $is_posts_page = false;
1083 * Resets query flags to false.
1085 * The query flags are what page info WordPress was able to figure out.
1090 function init_query_flags() {
1091 $this->is_single = false;
1092 $this->is_page = false;
1093 $this->is_archive = false;
1094 $this->is_date = false;
1095 $this->is_year = false;
1096 $this->is_month = false;
1097 $this->is_day = false;
1098 $this->is_time = false;
1099 $this->is_author = false;
1100 $this->is_category = false;
1101 $this->is_tag = false;
1102 $this->is_tax = false;
1103 $this->is_search = false;
1104 $this->is_feed = false;
1105 $this->is_comment_feed = false;
1106 $this->is_trackback = false;
1107 $this->is_home = false;
1108 $this->is_404 = false;
1109 $this->is_paged = false;
1110 $this->is_admin = false;
1111 $this->is_attachment = false;
1112 $this->is_singular = false;
1113 $this->is_robots = false;
1114 $this->is_posts_page = false;
1118 * Initiates object properties and sets default values.
1124 unset($this->posts);
1125 unset($this->query);
1126 $this->query_vars = array();
1127 unset($this->queried_object);
1128 unset($this->queried_object_id);
1129 $this->post_count = 0;
1130 $this->current_post = -1;
1131 $this->in_the_loop = false;
1133 $this->init_query_flags();
1137 * Reparse the query vars.
1142 function parse_query_vars() {
1143 $this->parse_query('');
1147 * Fills in the query variables, which do not exist within the parameter.
1152 * @param array $array Defined query variables.
1153 * @return array Complete query variables with undefined ones filled in empty.
1155 function fill_query_vars($array) {
1191 foreach ($keys as $key) {
1192 if ( !isset($array[$key]))
1196 $array_keys = array('category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in',
1197 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and');
1199 foreach ( $array_keys as $key ) {
1200 if ( !isset($array[$key]))
1201 $array[$key] = array();
1207 * Parse a query string and set query type booleans.
1212 * @param string|array $query
1214 function parse_query ($query) {
1215 if ( !empty($query) || !isset($this->query) ) {
1217 if ( is_array($query) )
1218 $this->query_vars = $query;
1220 parse_str($query, $this->query_vars);
1221 $this->query = $query;
1224 $this->query_vars = $this->fill_query_vars($this->query_vars);
1225 $qv = &$this->query_vars;
1227 if ( ! empty($qv['robots']) )
1228 $this->is_robots = true;
1230 $qv['p'] = absint($qv['p']);
1231 $qv['page_id'] = absint($qv['page_id']);
1232 $qv['year'] = absint($qv['year']);
1233 $qv['monthnum'] = absint($qv['monthnum']);
1234 $qv['day'] = absint($qv['day']);
1235 $qv['w'] = absint($qv['w']);
1236 $qv['m'] = absint($qv['m']);
1237 $qv['paged'] = absint($qv['paged']);
1238 $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers
1239 $qv['pagename'] = trim( $qv['pagename'] );
1240 $qv['name'] = trim( $qv['name'] );
1241 if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']);
1242 if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']);
1243 if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']);
1245 // Compat. Map subpost to attachment.
1246 if ( '' != $qv['subpost'] )
1247 $qv['attachment'] = $qv['subpost'];
1248 if ( '' != $qv['subpost_id'] )
1249 $qv['attachment_id'] = $qv['subpost_id'];
1251 $qv['attachment_id'] = absint($qv['attachment_id']);
1253 if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
1254 $this->is_single = true;
1255 $this->is_attachment = true;
1256 } elseif ( '' != $qv['name'] ) {
1257 $this->is_single = true;
1258 } elseif ( $qv['p'] ) {
1259 $this->is_single = true;
1260 } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
1261 // If year, month, day, hour, minute, and second are set, a single
1262 // post is being queried.
1263 $this->is_single = true;
1264 } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
1265 $this->is_page = true;
1266 $this->is_single = false;
1267 } elseif ( !empty($qv['s']) ) {
1268 $this->is_search = true;
1270 // Look for archive queries. Dates, categories, authors.
1272 if ( '' !== $qv['second'] ) {
1273 $this->is_time = true;
1274 $this->is_date = true;
1277 if ( '' !== $qv['minute'] ) {
1278 $this->is_time = true;
1279 $this->is_date = true;
1282 if ( '' !== $qv['hour'] ) {
1283 $this->is_time = true;
1284 $this->is_date = true;
1288 if (! $this->is_date) {
1289 $this->is_day = true;
1290 $this->is_date = true;
1294 if ( $qv['monthnum'] ) {
1295 if (! $this->is_date) {
1296 $this->is_month = true;
1297 $this->is_date = true;
1301 if ( $qv['year'] ) {
1302 if (! $this->is_date) {
1303 $this->is_year = true;
1304 $this->is_date = true;
1309 $this->is_date = true;
1310 if (strlen($qv['m']) > 9) {
1311 $this->is_time = true;
1312 } else if (strlen($qv['m']) > 7) {
1313 $this->is_day = true;
1314 } else if (strlen($qv['m']) > 5) {
1315 $this->is_month = true;
1317 $this->is_year = true;
1321 if ('' != $qv['w']) {
1322 $this->is_date = true;
1325 if ( empty($qv['cat']) || ($qv['cat'] == '0') ) {
1326 $this->is_category = false;
1328 if (strpos($qv['cat'], '-') !== false) {
1329 $this->is_category = false;
1331 $this->is_category = true;
1335 if ( '' != $qv['category_name'] ) {
1336 $this->is_category = true;
1339 if ( !is_array($qv['category__in']) || empty($qv['category__in']) ) {
1340 $qv['category__in'] = array();
1342 $qv['category__in'] = array_map('absint', $qv['category__in']);
1343 $this->is_category = true;
1346 if ( !is_array($qv['category__not_in']) || empty($qv['category__not_in']) ) {
1347 $qv['category__not_in'] = array();
1349 $qv['category__not_in'] = array_map('absint', $qv['category__not_in']);
1352 if ( !is_array($qv['category__and']) || empty($qv['category__and']) ) {
1353 $qv['category__and'] = array();
1355 $qv['category__and'] = array_map('absint', $qv['category__and']);
1356 $this->is_category = true;
1359 if ( '' != $qv['tag'] )
1360 $this->is_tag = true;
1362 $qv['tag_id'] = absint($qv['tag_id']);
1363 if ( !empty($qv['tag_id']) )
1364 $this->is_tag = true;
1366 if ( !is_array($qv['tag__in']) || empty($qv['tag__in']) ) {
1367 $qv['tag__in'] = array();
1369 $qv['tag__in'] = array_map('absint', $qv['tag__in']);
1370 $this->is_tag = true;
1373 if ( !is_array($qv['tag__not_in']) || empty($qv['tag__not_in']) ) {
1374 $qv['tag__not_in'] = array();
1376 $qv['tag__not_in'] = array_map('absint', $qv['tag__not_in']);
1379 if ( !is_array($qv['tag__and']) || empty($qv['tag__and']) ) {
1380 $qv['tag__and'] = array();
1382 $qv['tag__and'] = array_map('absint', $qv['tag__and']);
1383 $this->is_category = true;
1386 if ( !is_array($qv['tag_slug__in']) || empty($qv['tag_slug__in']) ) {
1387 $qv['tag_slug__in'] = array();
1389 $qv['tag_slug__in'] = array_map('sanitize_title', $qv['tag_slug__in']);
1390 $this->is_tag = true;
1393 if ( !is_array($qv['tag_slug__and']) || empty($qv['tag_slug__and']) ) {
1394 $qv['tag_slug__and'] = array();
1396 $qv['tag_slug__and'] = array_map('sanitize_title', $qv['tag_slug__and']);
1397 $this->is_tag = true;
1400 if ( empty($qv['taxonomy']) || empty($qv['term']) ) {
1401 $this->is_tax = false;
1402 foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) {
1403 if ( $t->query_var && isset($qv[$t->query_var]) && '' != $qv[$t->query_var] ) {
1404 $qv['taxonomy'] = $taxonomy;
1405 $qv['term'] = $qv[$t->query_var];
1406 $this->is_tax = true;
1411 $this->is_tax = true;
1414 if ( empty($qv['author']) || ($qv['author'] == '0') ) {
1415 $this->is_author = false;
1417 $this->is_author = true;
1420 if ( '' != $qv['author_name'] ) {
1421 $this->is_author = true;
1424 if ( ($this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax) )
1425 $this->is_archive = true;
1428 if ( '' != $qv['feed'] )
1429 $this->is_feed = true;
1431 if ( '' != $qv['tb'] )
1432 $this->is_trackback = true;
1434 if ( '' != $qv['paged'] )
1435 $this->is_paged = true;
1437 if ( '' != $qv['comments_popup'] )
1438 $this->is_comments_popup = true;
1440 // if we're previewing inside the write screen
1441 if ('' != $qv['preview'])
1442 $this->is_preview = true;
1445 $this->is_admin = true;
1447 if ( false !== strpos($qv['feed'], 'comments-') ) {
1448 $qv['feed'] = str_replace('comments-', '', $qv['feed']);
1449 $qv['withcomments'] = 1;
1452 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1454 if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
1455 $this->is_comment_feed = true;
1457 if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup || $this->is_robots ) )
1458 $this->is_home = true;
1460 // Correct is_* for page_on_front and page_for_posts
1461 if ( $this->is_home && ( empty($this->query) || $qv['preview'] == 'true' ) && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
1462 $this->is_page = true;
1463 $this->is_home = false;
1464 $qv['page_id'] = get_option('page_on_front');
1467 if ( '' != $qv['pagename'] ) {
1468 $this->queried_object =& get_page_by_path($qv['pagename']);
1469 if ( !empty($this->queried_object) )
1470 $this->queried_object_id = (int) $this->queried_object->ID;
1472 unset($this->queried_object);
1474 if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
1475 $this->is_page = false;
1476 $this->is_home = true;
1477 $this->is_posts_page = true;
1481 if ( $qv['page_id'] ) {
1482 if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
1483 $this->is_page = false;
1484 $this->is_home = true;
1485 $this->is_posts_page = true;
1489 if ( !empty($qv['post_type']) )
1490 $qv['post_type'] = sanitize_user($qv['post_type'], true);
1492 if ( !empty($qv['post_status']) )
1493 $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']);
1495 if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) )
1496 $this->is_comment_feed = false;
1498 $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
1499 // Done correcting is_* for page_on_front and page_for_posts
1501 if ('404' == $qv['error'])
1504 if ( !empty($query) )
1505 do_action_ref_array('parse_query', array(&$this));
1509 * Sets the 404 property and saves whether query is feed.
1514 function set_404() {
1515 $is_feed = $this->is_feed;
1517 $this->init_query_flags();
1518 $this->is_404 = true;
1520 $this->is_feed = $is_feed;
1524 * Retrieve query variable.
1529 * @param string $query_var Query variable key.
1532 function get($query_var) {
1533 if (isset($this->query_vars[$query_var])) {
1534 return $this->query_vars[$query_var];
1541 * Set query variable.
1546 * @param string $query_var Query variable key.
1547 * @param mixed $value Query variable value.
1549 function set($query_var, $value) {
1550 $this->query_vars[$query_var] = $value;
1554 * Retrieve the posts based on query variables.
1556 * There are a few filters and actions that can be used to modify the post
1561 * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts.
1563 * @return array List of posts.
1565 function &get_posts() {
1566 global $wpdb, $user_ID;
1568 do_action_ref_array('pre_get_posts', array(&$this));
1571 $q = &$this->query_vars;
1573 $q = $this->fill_query_vars($q);
1575 // First let's clear some variables
1579 $whichmimetype = '';
1585 $fields = "$wpdb->posts.*";
1586 $post_status_join = false;
1589 if ( !isset($q['caller_get_posts']) )
1590 $q['caller_get_posts'] = false;
1592 if ( !isset($q['suppress_filters']) )
1593 $q['suppress_filters'] = false;
1595 if ( !isset($q['post_type']) ) {
1596 if ( $this->is_search )
1597 $q['post_type'] = 'any';
1599 $q['post_type'] = 'post';
1601 $post_type = $q['post_type'];
1602 if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 )
1603 $q['posts_per_page'] = get_option('posts_per_page');
1604 if ( isset($q['showposts']) && $q['showposts'] ) {
1605 $q['showposts'] = (int) $q['showposts'];
1606 $q['posts_per_page'] = $q['showposts'];
1608 if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) )
1609 $q['posts_per_page'] = $q['posts_per_archive_page'];
1610 if ( !isset($q['nopaging']) ) {
1611 if ($q['posts_per_page'] == -1) {
1612 $q['nopaging'] = true;
1614 $q['nopaging'] = false;
1617 if ( $this->is_feed ) {
1618 $q['posts_per_page'] = get_option('posts_per_rss');
1619 $q['nopaging'] = false;
1621 $q['posts_per_page'] = (int) $q['posts_per_page'];
1622 if ( $q['posts_per_page'] < -1 )
1623 $q['posts_per_page'] = abs($q['posts_per_page']);
1624 else if ( $q['posts_per_page'] == 0 )
1625 $q['posts_per_page'] = 1;
1627 if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 )
1628 $q['comments_per_page'] = get_option('comments_per_page');
1630 if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) {
1631 $this->is_page = true;
1632 $this->is_home = false;
1633 $q['page_id'] = get_option('page_on_front');
1636 if (isset($q['page'])) {
1637 $q['page'] = trim($q['page'], '/');
1638 $q['page'] = absint($q['page']);
1641 // If a month is specified in the querystring, load that month
1643 $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
1644 $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4);
1645 if (strlen($q['m'])>5)
1646 $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2);
1647 if (strlen($q['m'])>7)
1648 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2);
1649 if (strlen($q['m'])>9)
1650 $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2);
1651 if (strlen($q['m'])>11)
1652 $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2);
1653 if (strlen($q['m'])>13)
1654 $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2);
1657 if ( '' !== $q['hour'] )
1658 $where .= " AND HOUR($wpdb->posts.post_date)='" . $q['hour'] . "'";
1660 if ( '' !== $q['minute'] )
1661 $where .= " AND MINUTE($wpdb->posts.post_date)='" . $q['minute'] . "'";
1663 if ( '' !== $q['second'] )
1664 $where .= " AND SECOND($wpdb->posts.post_date)='" . $q['second'] . "'";
1667 $where .= " AND YEAR($wpdb->posts.post_date)='" . $q['year'] . "'";
1669 if ( $q['monthnum'] )
1670 $where .= " AND MONTH($wpdb->posts.post_date)='" . $q['monthnum'] . "'";
1673 $where .= " AND DAYOFMONTH($wpdb->posts.post_date)='" . $q['day'] . "'";
1675 if ('' != $q['name']) {
1676 $q['name'] = sanitize_title($q['name']);
1677 $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'";
1678 } else if ('' != $q['pagename']) {
1679 if ( isset($this->queried_object_id) )
1680 $reqpage = $this->queried_object_id;
1682 $reqpage = get_page_by_path($q['pagename']);
1683 if ( !empty($reqpage) )
1684 $reqpage = $reqpage->ID;
1689 $page_for_posts = get_option('page_for_posts');
1690 if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) {
1691 $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
1692 $page_paths = '/' . trim($q['pagename'], '/');
1693 $q['pagename'] = sanitize_title(basename($page_paths));
1694 $q['name'] = $q['pagename'];
1695 $where .= " AND ($wpdb->posts.ID = '$reqpage')";
1696 $reqpage_obj = get_page($reqpage);
1697 if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) {
1698 $this->is_attachment = true;
1699 $this->is_page = true;
1700 $q['attachment_id'] = $reqpage;
1703 } elseif ('' != $q['attachment']) {
1704 $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment'])));
1705 $attach_paths = '/' . trim($q['attachment'], '/');
1706 $q['attachment'] = sanitize_title(basename($attach_paths));
1707 $q['name'] = $q['attachment'];
1708 $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'";
1712 $where .= " AND WEEK($wpdb->posts.post_date, 1)='" . $q['w'] . "'";
1714 if ( intval($q['comments_popup']) )
1715 $q['p'] = absint($q['comments_popup']);
1717 // If an attachment is requested by number, let it supercede any post number.
1718 if ( $q['attachment_id'] )
1719 $q['p'] = absint($q['attachment_id']);
1721 // If a post number is specified, load that post
1723 $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
1724 } elseif ( $q['post__in'] ) {
1725 $post__in = implode(',', array_map( 'absint', $q['post__in'] ));
1726 $where .= " AND {$wpdb->posts}.ID IN ($post__in)";
1727 } elseif ( $q['post__not_in'] ) {
1728 $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] ));
1729 $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)";
1732 if ( is_numeric($q['post_parent']) )
1733 $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] );
1735 if ( $q['page_id'] ) {
1736 if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
1737 $q['p'] = $q['page_id'];
1738 $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
1742 // If a search pattern is specified, load the posts that match
1743 if ( !empty($q['s']) ) {
1744 // added slashes screw with quote grouping when done early, so done later
1745 $q['s'] = stripslashes($q['s']);
1746 if ( !empty($q['sentence']) ) {
1747 $q['search_terms'] = array($q['s']);
1749 preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches);
1750 $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]);
1752 $n = !empty($q['exact']) ? '' : '%';
1754 foreach( (array) $q['search_terms'] as $term) {
1755 $term = addslashes_gpc($term);
1756 $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))";
1757 $searchand = ' AND ';
1759 $term = $wpdb->escape($q['s']);
1760 if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s'] )
1761 $search .= " OR ($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}')";
1763 if ( !empty($search) ) {
1764 $search = " AND ({$search}) ";
1765 if ( !is_user_logged_in() )
1766 $search .= " AND ($wpdb->posts.post_password = '') ";
1772 if ( empty($q['cat']) || ($q['cat'] == '0') ||
1773 // Bypass cat checks if fetching specific posts
1774 $this->is_singular ) {
1777 $q['cat'] = ''.urldecode($q['cat']).'';
1778 $q['cat'] = addslashes_gpc($q['cat']);
1779 $cat_array = preg_split('/[,\s]+/', $q['cat']);
1781 $req_cats = array();
1782 foreach ( (array) $cat_array as $cat ) {
1783 $cat = intval($cat);
1788 $q['category__in'][] = $cat;
1789 $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category'));
1791 $q['category__not_in'][] = $cat;
1792 $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category'));
1795 $q['cat'] = implode(',', $req_cats);
1798 if ( !empty($q['category__in']) ) {
1799 $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
1800 $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'category' ";
1801 $include_cats = "'" . implode("', '", $q['category__in']) . "'";
1802 $whichcat .= " AND $wpdb->term_taxonomy.term_id IN ($include_cats) ";
1805 if ( !empty($q['category__not_in']) ) {
1806 if ( $wpdb->has_cap( 'subqueries' ) ) {
1807 $cat_string = "'" . implode("', '", $q['category__not_in']) . "'";
1808 $whichcat .= " AND $wpdb->posts.ID NOT IN ( SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'category' AND tt.term_id IN ($cat_string) )";
1810 $ids = get_objects_in_term($q['category__not_in'], 'category');
1811 if ( !is_wp_error($ids) && is_array($ids) && count($ids) > 0 )
1812 $whichcat .= " AND $wpdb->posts.ID NOT IN ('" . implode("', '", $ids) . "')";
1816 // Category stuff for nice URLs
1817 if ( '' != $q['category_name'] && !$this->is_singular ) {
1818 $q['category_name'] = implode('/', array_map('sanitize_title', explode('/', $q['category_name'])));
1819 $reqcat = get_category_by_path($q['category_name']);
1820 $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
1821 $cat_paths = '/' . trim($q['category_name'], '/');
1822 $q['category_name'] = sanitize_title(basename($cat_paths));
1824 $cat_paths = '/' . trim(urldecode($q['category_name']), '/');
1825 $q['category_name'] = sanitize_title(basename($cat_paths));
1826 $cat_paths = explode('/', $cat_paths);
1828 foreach ( (array) $cat_paths as $pathdir )
1829 $cat_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title($pathdir);
1831 //if we don't match the entire hierarchy fallback on just matching the nicename
1832 if ( empty($reqcat) )
1833 $reqcat = get_category_by_path($q['category_name'], false);
1835 if ( !empty($reqcat) )
1836 $reqcat = $reqcat->term_id;
1840 $q['cat'] = $reqcat;
1842 $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
1843 $whichcat = " AND $wpdb->term_taxonomy.taxonomy = 'category' ";
1844 $in_cats = array($q['cat']);
1845 $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category'));
1846 $in_cats = "'" . implode("', '", $in_cats) . "'";
1847 $whichcat .= "AND $wpdb->term_taxonomy.term_id IN ($in_cats)";
1848 $groupby = "{$wpdb->posts}.ID";
1852 if ( '' != $q['tag'] ) {
1853 if ( strpos($q['tag'], ',') !== false ) {
1854 $tags = preg_split('/[,\s]+/', $q['tag']);
1855 foreach ( (array) $tags as $tag ) {
1856 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1857 $q['tag_slug__in'][] = $tag;
1859 } else if ( preg_match('/[+\s]+/', $q['tag']) || !empty($q['cat']) ) {
1860 $tags = preg_split('/[+\s]+/', $q['tag']);
1861 foreach ( (array) $tags as $tag ) {
1862 $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db');
1863 $q['tag_slug__and'][] = $tag;
1866 $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db');
1867 $q['tag_slug__in'][] = $q['tag'];
1871 if ( !empty($q['category__in']) || !empty($q['meta_key']) || !empty($q['tag__in']) || !empty($q['tag_slug__in']) ) {
1872 $groupby = "{$wpdb->posts}.ID";
1875 if ( !empty($q['tag__in']) && empty($q['cat']) ) {
1876 $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) ";
1877 $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'post_tag' ";
1878 $include_tags = "'" . implode("', '", $q['tag__in']) . "'";
1879 $whichcat .= " AND $wpdb->term_taxonomy.term_id IN ($include_tags) ";
1880 $reqtag = is_term( $q['tag__in'][0], 'post_tag' );
1881 if ( !empty($reqtag) )
1882 $q['tag_id'] = $reqtag['term_id'];
1885 if ( !empty($q['tag_slug__in']) && empty($q['cat']) ) {
1886 $join = " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) INNER JOIN $wpdb->terms ON ($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) ";
1887 $whichcat .= " AND $wpdb->term_taxonomy.taxonomy = 'post_tag' ";
1888 $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'";
1889 $whichcat .= " AND $wpdb->terms.slug IN ($include_tags) ";
1890 $reqtag = get_term_by( 'slug', $q['tag_slug__in'][0], 'post_tag' );
1891 if ( !empty($reqtag) )
1892 $q['tag_id'] = $reqtag->term_id;
1895 if ( !empty($q['tag__not_in']) ) {
1896 if ( $wpdb->has_cap( 'subqueries' ) ) {
1897 $tag_string = "'" . implode("', '", $q['tag__not_in']) . "'";
1898 $whichcat .= " AND $wpdb->posts.ID NOT IN ( SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy = 'post_tag' AND tt.term_id IN ($tag_string) )";
1900 $ids = get_objects_in_term($q['tag__not_in'], 'post_tag');
1901 if ( !is_wp_error($ids) && is_array($ids) && count($ids) > 0 )
1902 $whichcat .= " AND $wpdb->posts.ID NOT IN ('" . implode("', '", $ids) . "')";
1906 // Tag and slug intersections.
1907 $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag', 'tag__in' => 'post_tag', 'tag_slug__in' => 'post_tag');
1908 $tagin = array('tag__in', 'tag_slug__in'); // These are used to make some exceptions below
1909 foreach ($intersections as $item => $taxonomy) {
1910 if ( empty($q[$item]) ) continue;
1911 if ( in_array($item, $tagin) && empty($q['cat']) ) continue; // We should already have what we need if categories aren't being used
1913 if ( $item != 'category__and' ) {
1914 $reqtag = is_term( $q[$item][0], 'post_tag' );
1915 if ( !empty($reqtag) )
1916 $q['tag_id'] = $reqtag['term_id'];
1919 if ( in_array( $item, array('tag_slug__and', 'tag_slug__in' ) ) )
1920 $taxonomy_field = 'slug';
1922 $taxonomy_field = 'term_id';
1924 $q[$item] = array_unique($q[$item]);
1925 $tsql = "SELECT p.ID FROM $wpdb->posts p INNER JOIN $wpdb->term_relationships tr ON (p.ID = tr.object_id) INNER JOIN $wpdb->term_taxonomy tt ON (tr.term_taxonomy_id = tt.term_taxonomy_id) INNER JOIN $wpdb->terms t ON (tt.term_id = t.term_id)";
1926 $tsql .= " WHERE tt.taxonomy = '$taxonomy' AND t.$taxonomy_field IN ('" . implode("', '", $q[$item]) . "')";
1927 if ( !in_array($item, $tagin) ) { // This next line is only helpful if we are doing an and relationship
1928 $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]);
1930 $post_ids = $wpdb->get_col($tsql);
1932 if ( count($post_ids) )
1933 $whichcat .= " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
1935 $whichcat = " AND 0 = 1";
1941 if ( $this->is_tax ) {
1942 if ( '' != $q['taxonomy'] ) {
1943 $taxonomy = $q['taxonomy'];
1944 $tt[$taxonomy] = $q['term'];
1945 $terms = get_terms($q['taxonomy'], array('slug'=>$q['term']));
1947 foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) {
1948 if ( $t->query_var && '' != $q[$t->query_var] ) {
1949 $terms = get_terms($taxonomy, array('slug'=>$q[$t->query_var]));
1950 if ( !is_wp_error($terms) )
1955 if ( is_wp_error($terms) || empty($terms) ) {
1956 $whichcat = " AND 0 ";
1958 foreach ( $terms as $term )
1959 $term_ids[] = $term->term_id;
1960 $post_ids = get_objects_in_term($term_ids, $taxonomy);
1961 if ( !is_wp_error($post_ids) && count($post_ids) ) {
1962 $whichcat .= " AND $wpdb->posts.ID IN (" . implode(', ', $post_ids) . ") ";
1964 $q['post_status'] = 'publish';
1965 $post_status_join = true;
1967 $whichcat = " AND 0 ";
1972 // Author/user stuff
1974 if ( empty($q['author']) || ($q['author'] == '0') ) {
1977 $q['author'] = ''.urldecode($q['author']).'';
1978 $q['author'] = addslashes_gpc($q['author']);
1979 if (strpos($q['author'], '-') !== false) {
1982 $q['author'] = explode('-', $q['author']);
1983 $q['author'] = '' . absint($q['author'][1]);
1988 $author_array = preg_split('/[,\s]+/', $q['author']);
1989 $whichauthor .= " AND ($wpdb->posts.post_author ".$eq.' '.absint($author_array[0]);
1990 for ($i = 1; $i < (count($author_array)); $i = $i + 1) {
1991 $whichauthor .= ' '.$andor." $wpdb->posts.post_author ".$eq.' '.absint($author_array[$i]);
1993 $whichauthor .= ')';
1996 // Author stuff for nice URLs
1998 if ('' != $q['author_name']) {
1999 if (strpos($q['author_name'], '/') !== false) {
2000 $q['author_name'] = explode('/',$q['author_name']);
2001 if ($q['author_name'][count($q['author_name'])-1]) {
2002 $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash
2004 $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash
2007 $q['author_name'] = sanitize_title($q['author_name']);
2008 $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'");
2009 $q['author'] = get_user_by('slug', $q['author_name']);
2011 $q['author'] = $q['author']->ID;
2012 $whichauthor .= " AND ($wpdb->posts.post_author = ".absint($q['author']).')';
2015 // MIME-Type stuff for attachment browsing
2017 if ( isset($q['post_mime_type']) && '' != $q['post_mime_type'] )
2018 $whichmimetype = wp_post_mime_type_where($q['post_mime_type']);
2020 $where .= $search.$whichcat.$whichauthor.$whichmimetype;
2022 if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) )
2023 $q['order'] = 'DESC';
2026 if ( empty($q['orderby']) ) {
2027 $q['orderby'] = "$wpdb->posts.post_date ".$q['order'];
2028 } elseif ( 'none' == $q['orderby'] ) {
2031 // Used to filter values
2032 $allowed_keys = array('author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand');
2033 if ( !empty($q['meta_key']) ) {
2034 $allowed_keys[] = $q['meta_key'];
2035 $allowed_keys[] = 'meta_value';
2037 $q['orderby'] = urldecode($q['orderby']);
2038 $q['orderby'] = addslashes_gpc($q['orderby']);
2039 $orderby_array = explode(' ',$q['orderby']);
2040 if ( empty($orderby_array) )
2041 $orderby_array[] = $q['orderby'];
2043 for ($i = 0; $i < count($orderby_array); $i++) {
2044 // Only allow certain values for safety
2045 $orderby = $orderby_array[$i];
2050 $orderby = "$wpdb->posts.ID";
2053 $orderby = 'RAND()';
2055 case $q['meta_key']:
2057 $orderby = "$wpdb->postmeta.meta_value";
2060 $orderby = "$wpdb->posts.post_" . $orderby;
2062 if ( in_array($orderby_array[$i], $allowed_keys) )
2063 $q['orderby'] .= (($i == 0) ? '' : ',') . $orderby;
2065 // append ASC or DESC at the end
2066 if ( !empty($q['orderby']))
2067 $q['orderby'] .= " {$q['order']}";
2069 if ( empty($q['orderby']) )
2070 $q['orderby'] = "$wpdb->posts.post_date ".$q['order'];
2073 if ( 'any' == $post_type ) {
2074 $where .= " AND $wpdb->posts.post_type != 'revision'";
2075 } elseif ( $this->is_attachment ) {
2076 $where .= " AND $wpdb->posts.post_type = 'attachment'";
2077 } elseif ($this->is_page) {
2078 $where .= " AND $wpdb->posts.post_type = 'page'";
2079 } elseif ($this->is_single) {
2080 $where .= " AND $wpdb->posts.post_type = 'post'";
2082 $where .= " AND $wpdb->posts.post_type = '$post_type'";
2085 if ( isset($q['post_status']) && '' != $q['post_status'] ) {
2086 $statuswheres = array();
2087 $q_status = explode(',', $q['post_status']);
2088 $r_status = array();
2089 $p_status = array();
2090 if ( in_array( 'draft' , $q_status ) )
2091 $r_status[] = "$wpdb->posts.post_status = 'draft'";
2092 if ( in_array( 'pending', $q_status ) )
2093 $r_status[] = "$wpdb->posts.post_status = 'pending'";
2094 if ( in_array( 'future' , $q_status ) )
2095 $r_status[] = "$wpdb->posts.post_status = 'future'";
2096 if ( in_array( 'inherit' , $q_status ) )
2097 $r_status[] = "$wpdb->posts.post_status = 'inherit'";
2098 if ( in_array( 'private', $q_status ) )
2099 $p_status[] = "$wpdb->posts.post_status = 'private'";
2100 if ( in_array( 'publish', $q_status ) )
2101 $r_status[] = "$wpdb->posts.post_status = 'publish'";
2103 if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) {
2104 $r_status = array_merge($r_status, $p_status);
2108 if ( !empty($r_status) ) {
2109 if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can("edit_others_{$post_type}s") )
2110 $statuswheres[] = "($wpdb->posts.post_author = $user_ID " . "AND (" . join( ' OR ', $r_status ) . "))";
2112 $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")";
2114 if ( !empty($p_status) ) {
2115 if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can("read_private_{$post_type}s") )
2116 $statuswheres[] = "($wpdb->posts.post_author = $user_ID " . "AND (" . join( ' OR ', $p_status ) . "))";
2118 $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")";
2120 if ( $post_status_join ) {
2121 $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) ";
2122 foreach ( $statuswheres as $index => $statuswhere )
2123 $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
2125 foreach ( $statuswheres as $statuswhere )
2126 $where .= " AND $statuswhere";
2127 } elseif ( !$this->is_singular ) {
2128 $where .= " AND ($wpdb->posts.post_status = 'publish'";
2131 $where .= " OR $wpdb->posts.post_status = 'future' OR $wpdb->posts.post_status = 'draft' OR $wpdb->posts.post_status = 'pending'";
2133 if ( is_user_logged_in() ) {
2134 $where .= current_user_can( "read_private_{$post_type}s" ) ? " OR $wpdb->posts.post_status = 'private'" : " OR $wpdb->posts.post_author = $user_ID AND $wpdb->posts.post_status = 'private'";
2141 if ( ! empty($q['meta_key']) || ! empty($q['meta_value']) )
2142 $join .= " JOIN $wpdb->postmeta ON ($wpdb->posts.ID = $wpdb->postmeta.post_id) ";
2143 if ( ! empty($q['meta_key']) )
2144 $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s ", $q['meta_key']);
2145 if ( ! empty($q['meta_value']) ) {
2146 if ( ! isset($q['meta_compare']) || empty($q['meta_compare']) || ! in_array($q['meta_compare'], array('=', '!=', '>', '>=', '<', '<=')) )
2147 $q['meta_compare'] = '=';
2149 $where .= $wpdb->prepare("AND $wpdb->postmeta.meta_value {$q['meta_compare']} %s ", $q['meta_value']);
2152 // Apply filters on where and join prior to paging so that any
2153 // manipulations to them are reflected in the paging by day queries.
2154 if ( !$q['suppress_filters'] ) {
2155 $where = apply_filters('posts_where', $where);
2156 $join = apply_filters('posts_join', $join);
2160 if ( empty($q['nopaging']) && !$this->is_singular ) {
2161 $page = absint($q['paged']);
2166 if ( empty($q['offset']) ) {
2168 $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
2169 $limits = 'LIMIT '.$pgstrt.$q['posts_per_page'];
2170 } else { // we're ignoring $page and using 'offset'
2171 $q['offset'] = absint($q['offset']);
2172 $pgstrt = $q['offset'] . ', ';
2173 $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
2178 if ( $this->is_comment_feed && ( $this->is_archive || $this->is_search || !$this->is_singular ) ) {
2179 if ( $this->is_archive || $this->is_search ) {
2180 $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
2181 $cwhere = "WHERE comment_approved = '1' $where";
2182 $cgroupby = "$wpdb->comments.comment_id";
2183 } else { // Other non singular e.g. front
2184 $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
2185 $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
2189 if ( !$q['suppress_filters'] ) {
2190 $cjoin = apply_filters('comment_feed_join', $cjoin);
2191 $cwhere = apply_filters('comment_feed_where', $cwhere);
2192 $cgroupby = apply_filters('comment_feed_groupby', $cgroupby);
2193 $corderby = apply_filters('comment_feed_orderby', 'comment_date_gmt DESC');
2194 $climits = apply_filters('comment_feed_limits', 'LIMIT ' . get_option('posts_per_rss'));
2196 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
2197 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
2199 $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits");
2200 $this->comment_count = count($this->comments);
2202 $post_ids = array();
2204 foreach ($this->comments as $comment)
2205 $post_ids[] = (int) $comment->comment_post_ID;
2207 $post_ids = join(',', $post_ids);
2210 $where = "AND $wpdb->posts.ID IN ($post_ids) ";
2215 $orderby = $q['orderby'];
2217 // Apply post-paging filters on where and join. Only plugins that
2218 // manipulate paging queries should use these hooks.
2219 if ( !$q['suppress_filters'] ) {
2220 $where = apply_filters('posts_where_paged', $where);
2221 $groupby = apply_filters('posts_groupby', $groupby);
2222 $join = apply_filters('posts_join_paged', $join);
2223 $orderby = apply_filters('posts_orderby', $orderby);
2224 $distinct = apply_filters('posts_distinct', $distinct);
2225 $limits = apply_filters( 'post_limits', $limits );
2227 $fields = apply_filters('posts_fields', $fields);
2230 // Announce current selection parameters. For use by caching plugins.
2231 do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join );
2233 // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above.
2234 if ( !$q['suppress_filters'] ) {
2235 $where = apply_filters('posts_where_request', $where);
2236 $groupby = apply_filters('posts_groupby_request', $groupby);
2237 $join = apply_filters('posts_join_request', $join);
2238 $orderby = apply_filters('posts_orderby_request', $orderby);
2239 $distinct = apply_filters('posts_distinct_request', $distinct);
2240 $fields = apply_filters('posts_fields_request', $fields);
2241 $limits = apply_filters( 'post_limits_request', $limits );
2244 if ( ! empty($groupby) )
2245 $groupby = 'GROUP BY ' . $groupby;
2246 if ( !empty( $orderby ) )
2247 $orderby = 'ORDER BY ' . $orderby;
2249 if ( !empty($limits) )
2250 $found_rows = 'SQL_CALC_FOUND_ROWS';
2252 $this->request = " SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits";
2253 if ( !$q['suppress_filters'] )
2254 $this->request = apply_filters('posts_request', $this->request);
2256 $this->posts = $wpdb->get_results($this->request);
2257 // Raw results filter. Prior to status checks.
2258 if ( !$q['suppress_filters'] )
2259 $this->posts = apply_filters('posts_results', $this->posts);
2261 if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) {
2262 $cjoin = apply_filters('comment_feed_join', '');
2263 $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'");
2264 $cgroupby = apply_filters('comment_feed_groupby', '');
2265 $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : '';
2266 $corderby = apply_filters('comment_feed_orderby', 'comment_date_gmt DESC');
2267 $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : '';
2268 $climits = apply_filters('comment_feed_limits', 'LIMIT ' . get_option('posts_per_rss'));
2269 $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits";
2270 $this->comments = $wpdb->get_results($comments_request);
2271 $this->comment_count = count($this->comments);
2274 if ( !empty($limits) ) {
2275 $found_posts_query = apply_filters( 'found_posts_query', 'SELECT FOUND_ROWS()' );
2276 $this->found_posts = $wpdb->get_var( $found_posts_query );
2277 $this->found_posts = apply_filters( 'found_posts', $this->found_posts );
2278 $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
2281 // Check post status to determine if post should be displayed.
2282 if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
2283 $status = get_post_status($this->posts[0]);
2284 //$type = get_post_type($this->posts[0]);
2285 if ( ('publish' != $status) ) {
2286 if ( ! is_user_logged_in() ) {
2287 // User must be logged in to view unpublished posts.
2288 $this->posts = array();
2290 if (in_array($status, array('draft', 'pending')) ) {
2291 // User must have edit permissions on the draft to preview.
2292 if (! current_user_can('edit_post', $this->posts[0]->ID)) {
2293 $this->posts = array();
2295 $this->is_preview = true;
2296 $this->posts[0]->post_date = current_time('mysql');
2298 } else if ('future' == $status) {
2299 $this->is_preview = true;
2300 if (!current_user_can('edit_post', $this->posts[0]->ID)) {
2301 $this->posts = array ( );
2304 if (! current_user_can('read_post', $this->posts[0]->ID))
2305 $this->posts = array();
2310 if ( $this->is_preview && current_user_can( "edit_{$post_type}", $this->posts[0]->ID ) )
2311 $this->posts[0] = apply_filters('the_preview', $this->posts[0]);
2314 // Put sticky posts at the top of the posts array
2315 $sticky_posts = get_option('sticky_posts');
2316 if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['caller_get_posts'] ) {
2317 $num_posts = count($this->posts);
2319 // Loop over posts and relocate stickies to the front.
2320 for ( $i = 0; $i < $num_posts; $i++ ) {
2321 if ( in_array($this->posts[$i]->ID, $sticky_posts) ) {
2322 $sticky_post = $this->posts[$i];
2323 // Remove sticky from current position
2324 array_splice($this->posts, $i, 1);
2325 // Move to front, after other stickies
2326 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
2327 // Increment the sticky offset. The next sticky will be placed at this offset.
2329 // Remove post from sticky posts array
2330 $offset = array_search($sticky_post->ID, $sticky_posts);
2331 array_splice($sticky_posts, $offset, 1);
2335 // Fetch sticky posts that weren't in the query results
2336 if ( !empty($sticky_posts) ) {
2337 $stickies__in = implode(',', array_map( 'absint', $sticky_posts ));
2338 $stickies = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE $wpdb->posts.ID IN ($stickies__in)" );
2339 /** @todo Make sure post is published or viewable by the current user */
2340 foreach ( $stickies as $sticky_post ) {
2341 if ( 'publish' != $sticky_post->post_status )
2343 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
2349 if ( !$q['suppress_filters'] )
2350 $this->posts = apply_filters('the_posts', $this->posts);
2352 update_post_caches($this->posts);
2354 $this->post_count = count($this->posts);
2355 if ($this->post_count > 0) {
2356 $this->post = $this->posts[0];
2359 return $this->posts;
2363 * Setup the next post and iterate current post index.
2368 * @return object Next post.
2370 function next_post() {
2372 $this->current_post++;
2374 $this->post = $this->posts[$this->current_post];
2379 * Sets up the current post.
2381 * Retrieves the next post, sets up the post, sets the 'in the loop'
2387 * @uses do_action_ref_array() Calls 'loop_start' if loop has just started
2389 function the_post() {
2391 $this->in_the_loop = true;
2393 if ( $this->current_post == -1 ) // loop has just started
2394 do_action_ref_array('loop_start', array(&$this));
2396 $post = $this->next_post();
2397 setup_postdata($post);
2401 * Whether there are more posts available in the loop.
2403 * Calls action 'loop_end', when the loop is complete.
2407 * @uses do_action_ref_array() Calls 'loop_end' if loop is ended
2409 * @return bool True if posts are available, false if end of loop.
2411 function have_posts() {
2412 if ($this->current_post + 1 < $this->post_count) {
2414 } elseif ($this->current_post + 1 == $this->post_count && $this->post_count > 0) {
2415 do_action_ref_array('loop_end', array(&$this));
2416 // Do some cleaning up after the loop
2417 $this->rewind_posts();
2420 $this->in_the_loop = false;
2425 * Rewind the posts and reset post index.
2430 function rewind_posts() {
2431 $this->current_post = -1;
2432 if ($this->post_count > 0) {
2433 $this->post = $this->posts[0];
2438 * Iterate current comment index and return comment object.
2443 * @return object Comment object.
2445 function next_comment() {
2446 $this->current_comment++;
2448 $this->comment = $this->comments[$this->current_comment];
2449 return $this->comment;
2453 * Sets up the current comment.
2457 * @global object $comment Current comment.
2458 * @uses do_action() Calls 'comment_loop_start' hook when first comment is processed.
2460 function the_comment() {
2463 $comment = $this->next_comment();
2465 if ($this->current_comment == 0) {
2466 do_action('comment_loop_start');
2471 * Whether there are more comments available.
2473 * Automatically rewinds comments when finished.
2478 * @return bool True, if more comments. False, if no more posts.
2480 function have_comments() {
2481 if ($this->current_comment + 1 < $this->comment_count) {
2483 } elseif ($this->current_comment + 1 == $this->comment_count) {
2484 $this->rewind_comments();
2491 * Rewind the comments, resets the comment index and comment to first.
2496 function rewind_comments() {
2497 $this->current_comment = -1;
2498 if ($this->comment_count > 0) {
2499 $this->comment = $this->comments[0];
2504 * Sets up the WordPress query by parsing query string.
2509 * @param string $query URL query string.
2510 * @return array List of posts.
2512 function &query($query) {
2513 $this->parse_query($query);
2514 return $this->get_posts();
2518 * Retrieve queried object.
2520 * If queried object is not set, then the queried object will be set from
2521 * the category, tag, taxonomy, posts page, single post, page, or author
2522 * query variable. After it is set up, it will be returned.
2529 function get_queried_object() {
2530 if (isset($this->queried_object)) {
2531 return $this->queried_object;
2534 $this->queried_object = NULL;
2535 $this->queried_object_id = 0;
2537 if ($this->is_category) {
2538 $cat = $this->get('cat');
2539 $category = &get_category($cat);
2540 if ( is_wp_error( $category ) )
2542 $this->queried_object = &$category;
2543 $this->queried_object_id = (int) $cat;
2544 } else if ($this->is_tag) {
2545 $tag_id = $this->get('tag_id');
2546 $tag = &get_term($tag_id, 'post_tag');
2547 if ( is_wp_error( $tag ) )
2549 $this->queried_object = &$tag;
2550 $this->queried_object_id = (int) $tag_id;
2551 } else if ($this->is_tax) {
2552 $tax = $this->get('taxonomy');
2553 $slug = $this->get('term');
2554 $term = &get_terms($tax, array('slug'=>$slug));
2555 if ( is_wp_error($term) || empty($term) )
2558 $this->queried_object = $term;
2559 $this->queried_object_id = $term->term_id;
2560 } else if ($this->is_posts_page) {
2561 $this->queried_object = & get_page(get_option('page_for_posts'));
2562 $this->queried_object_id = (int) $this->queried_object->ID;
2563 } else if ($this->is_single) {
2564 $this->queried_object = $this->post;
2565 $this->queried_object_id = (int) $this->post->ID;
2566 } else if ($this->is_page) {
2567 $this->queried_object = $this->post;
2568 $this->queried_object_id = (int) $this->post->ID;
2569 } else if ($this->is_author) {
2570 $author_id = (int) $this->get('author');
2571 $author = get_userdata($author_id);
2572 $this->queried_object = $author;
2573 $this->queried_object_id = $author_id;
2576 return $this->queried_object;
2580 * Retrieve ID of the current queried object.
2587 function get_queried_object_id() {
2588 $this->get_queried_object();
2590 if (isset($this->queried_object_id)) {
2591 return $this->queried_object_id;
2598 * PHP4 type constructor.
2600 * Sets up the WordPress query, if parameter is not empty.
2605 * @param string $query URL query string.
2608 function WP_Query ($query = '') {
2609 if (! empty($query)) {
2610 $this->query($query);
2616 * Redirect old slugs to the correct permalink.
2618 * Attempts to find the current slug from the past slugs.
2624 * @return null If no link is found, null is returned.
2626 function wp_old_slug_redirect () {
2628 if ( is_404() && '' != $wp_query->query_vars['name'] ) :
2631 $query = "SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND meta_key = '_wp_old_slug' AND meta_value='" . $wp_query->query_vars['name'] . "'";
2633 // if year, monthnum, or day have been specified, make our query more precise
2634 // just in case there are multiple identical _wp_old_slug values
2635 if ( '' != $wp_query->query_vars['year'] )
2636 $query .= " AND YEAR(post_date) = '{$wp_query->query_vars['year']}'";
2637 if ( '' != $wp_query->query_vars['monthnum'] )
2638 $query .= " AND MONTH(post_date) = '{$wp_query->query_vars['monthnum']}'";
2639 if ( '' != $wp_query->query_vars['day'] )
2640 $query .= " AND DAYOFMONTH(post_date) = '{$wp_query->query_vars['day']}'";
2642 $id = (int) $wpdb->get_var($query);
2647 $link = get_permalink($id);
2652 wp_redirect($link, '301'); // Permanent redirect
2658 * Setup global post data.
2662 * @param object $post Post data.
2663 * @uses do_action_ref_array() Calls 'the_post'
2664 * @return bool True when finished.
2666 function setup_postdata($post) {
2667 global $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages;
2669 $id = (int) $post->ID;
2671 $authordata = get_userdata($post->post_author);
2673 $day = mysql2date('d.m.y', $post->post_date, false);
2674 $currentmonth = mysql2date('m', $post->post_date, false);
2676 $page = get_query_var('page');
2679 if ( is_single() || is_page() || is_feed() )
2681 $content = $post->post_content;
2682 if ( strpos( $content, '<!--nextpage-->' ) ) {
2686 $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
2687 $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
2688 $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
2689 $pages = explode('<!--nextpage-->', $content);
2690 $numpages = count($pages);
2692 $pages[0] = $post->post_content;
2696 do_action_ref_array('the_post', array(&$post));