/** * Display the widget */ function widget($args, $instance) { global $wp_query, $post; extract($args); echo $before_widget; // Title $title = apply_filters('widget_title', $instance['title']); if (!empty($title)) { echo $before_title . $title . $after_title; } // Number of posts if (!($number = (int) $instance['number'])) { $number = 5; } else { if ($number < 1) { $number = 1; } else { if ($number > 15) { $number = 15; } } } // Create Query $posts_query = array('post__in' => get_option('sticky_posts'), 'posts_per_page' => $number, 'orderby' => 'date', 'post_status' => 'publish'); $sticky_posts = new WP_Query($posts_query); // The Loop echo '<ul>'; while ($sticky_posts->have_posts()) { $sticky_posts->the_post(); update_post_caches($posts); echo '<li>'; if (locate_template(array('themeable-sticky-post.php', 'themeable-sticky-post-widget.php'))) { get_template_part('themeable-sticky-post', 'widget'); } else { $plugin_templates_path = WP_PLUGIN_DIR . '/' . str_replace(basename(__FILE__), '', plugin_basename(__FILE__)) . 'templates/'; include $plugin_templates_path . 'list.php'; } echo '</li>'; } $post = $wp_query->post; setup_postdata($post); echo '</ul>'; echo $after_widget; }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @todo determine early if the query can be run using ES, otherwise defer to WP_Query * * @return array List of posts. */ public function get_posts() { global $wpdb; /** * In addition to what's below, other fields include: * post_id * post_author * post_author.user_nicename * post_date * post_date.year * post_date.month * post_date.week * post_date.day * post_date.day_of_year * post_date.day_of_week * post_date.hour * post_date.minute * post_date.second * post_date_gmt (plus all the same tokens as post_date) * post_content * post_content.analyzed * post_title * post_title.analyzed * post_excerpt * post_status * ping_status * post_password * post_name * post_modified (plus all the same tokens as post_date) * post_modified_gmt (plus all the same tokens as post_date) * post_parent * menu_order * post_type * post_mime_type * comment_count */ $this->es_map = apply_filters('es_field_map', array('post_meta' => 'post_meta.%s', 'post_meta.analyzed' => 'post_meta.%s.analyzed', 'post_meta.long' => 'post_meta.%s.long', 'post_meta.double' => 'post_meta.%s.double', 'post_meta.binary' => 'post_meta.%s.boolean', 'post_meta.date' => 'post_meta.%s.date', 'post_meta.datetime' => 'post_meta.%s.datetime', 'post_meta.time' => 'post_meta.%s.time', 'post_meta.signed' => 'post_meta.%s.signed', 'post_meta.unsigned' => 'post_meta.%s.unsigned', 'term_id' => 'terms.%s.term_id', 'term_slug' => 'terms.%s.slug', 'term_name' => 'terms.%s.name', 'term_tt_id' => 'terms.%s.term_taxonomy_id', 'category_id' => 'terms.%s.term_id', 'category_slug' => 'terms.%s.slug', 'category_name' => 'terms.%s.name', 'category_tt_id' => 'terms.%s.term_taxonomy_id', 'tag_id' => 'terms.%s.term_id', 'tag_slug' => 'terms.%s.slug', 'tag_name' => 'terms.%s.name', 'tag_tt_id' => 'terms.%s.term_taxonomy_id')); $this->parse_query(); if (isset($this->query_vars['es'])) { unset($this->query_vars['es']); } do_action_ref_array('pre_get_posts', array(&$this)); do_action_ref_array('es_pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new ES_WP_Meta_Query(); $this->meta_query->parse_query_vars($q); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5(serialize($this->query_vars)); if ($hash != $this->query_vars_hash) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $post_status_join = false; $page = 1; // ES $filter = array(); $query = array(); $sort = array(); $fields = array(); $from = 0; $size = 10; if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['cache_results'])) { if (wp_using_ext_object_cache()) { $q['cache_results'] = false; } else { $q['cache_results'] = true; } } if (!isset($q['update_post_term_cache'])) { $q['update_post_term_cache'] = true; } if (!isset($q['update_post_meta_cache'])) { $q['update_post_meta_cache'] = true; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = ''; } } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } switch ($q['fields']) { case 'ids': $fields = array($this->es_map('post_id')); break; case 'id=>parent': $fields = array($this->es_map('post_id'), $this->es_map('post_parent')); break; default: if (apply_filters('es_query_use_source', false)) { $fields = array('_source'); } else { $fields = array($this->es_map('post_id')); } } if ('' !== $q['menu_order']) { $filter[] = $this->dsl_terms($this->es_map('menu_order'), $q['menu_order']); } // The "m" parameter is meant for months but accepts datetimes of varying specificity if ($q['m']) { $date = array('year' => substr($q['m'], 0, 4)); $m_len = strlen($q['m']); if ($m_len > 5) { $date['month'] = substr($q['m'], 4, 2); } if ($m_len > 7) { $date['day'] = substr($q['m'], 6, 2); } if ($m_len > 9) { $date['hour'] = substr($q['m'], 8, 2); } if ($m_len > 11) { $date['minute'] = substr($q['m'], 10, 2); } if ($m_len > 13) { $date['second'] = substr($q['m'], 12, 2); // If we have absolute precision, we can use a term filter instead of a range $filter[] = $this->dsl_terms($this->es_map('post_date'), ES_WP_Date_Query::build_datetime($date)); } else { // We don't have second-level precision, so we need to build a range query from what we have $date_query = new ES_WP_Date_Query(array('after' => $date, 'before' => $date, 'inclusive' => true)); $date_filter = $date_query->get_dsl($this); if (!empty($date_filter)) { $filter[] = $date_filter; } elseif (false === $date_filter) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } } } unset($date_query, $date_filter, $date, $m_len); // Handle the other individual date parameters $date_parameters = array(); if ('' !== $q['hour']) { $date_parameters['hour'] = $q['hour']; } if ('' !== $q['minute']) { $date_parameters['minute'] = $q['minute']; } if ('' !== $q['second']) { $date_parameters['second'] = $q['second']; } if ($q['year']) { $date_parameters['year'] = $q['year']; } if ($q['monthnum']) { $date_parameters['month'] = $q['monthnum']; } if ($q['w']) { $date_parameters['week'] = $q['w']; } if ($q['day']) { $date_parameters['day'] = $q['day']; } if ($date_parameters) { $date_query = new ES_WP_Date_Query(array($date_parameters)); $date_filter = $date_query->get_dsl($this); if (!empty($date_filter)) { $filter[] = $date_filter; } elseif (false === $date_filter) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } } unset($date_parameters, $date_query, $date_filter); // Handle complex date queries if (!empty($q['date_query'])) { $this->date_query = new ES_WP_Date_Query($q['date_query']); $date_filter = $this->date_query->get_dsl($this); if (!empty($date_filter)) { $filter[] = $date_filter; } elseif (false === $date_filter) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } unset($date_filter); } // If we've got a post_type AND it's not "any" post_type. if (!empty($q['post_type']) && 'any' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) { continue; } if (!$ptype_obj->hierarchical || strpos($q[$ptype_obj->query_var], '/') === false) { // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name' $q['name'] = $q[$ptype_obj->query_var]; } else { // Hierarchical post_types will operate through the $q['pagename'] = $q[$ptype_obj->query_var]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ('' != $q['name']) { $q['name'] = sanitize_title_for_query($q['name']); $filter[] = $this->dsl_terms($this->es_map('post_name'), $q['name']); } elseif ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { if ('page' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->hierarchical) { continue; } $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ($reqpage) { break; } } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename'])); $q['name'] = $q['pagename']; $filter[] = $this->dsl_terms($this->es_map('post_id'), absint($reqpage)); $reqpage_obj = get_post($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment'])); $q['name'] = $q['attachment']; $filter[] = $this->dsl_terms($this->es_map('post_name'), $q['attachment']); } if (isset($q['comments_popup']) && intval($q['comments_popup'])) { $q['p'] = absint($q['comments_popup']); } // If an attachment is requested by number, let it supersede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $filter[] = $this->dsl_terms($this->es_map('post_id'), absint($q['p'])); } elseif ($q['post__in']) { $post__in = array_map('absint', $q['post__in']); $filter[] = $this->dsl_terms($this->es_map('post_id'), $post__in); } elseif ($q['post__not_in']) { $post__not_in = array_map('absint', $q['post__not_in']); $filter[] = array('not' => $this->dsl_terms($this->es_map('post_id'), $post__not_in)); } if (is_numeric($q['post_parent'])) { $filter[] = $this->dsl_terms($this->es_map('post_parent'), absint($q['post_parent'])); } elseif ($q['post_parent__in']) { $post_parent__in = array_map('absint', $q['post_parent__in']); $filter[] = $this->dsl_terms($this->es_map('post_parent'), $post_parent__in); } elseif ($q['post_parent__not_in']) { $post_parent__not_in = array_map('absint', $q['post_parent__not_in']); $filter[] = array('not' => $this->dsl_terms($this->es_map('post_parent'), $post_parent__not_in)); } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $filter[] = $this->dsl_terms($this->es_map('post_id'), absint($q['page_id'])); } } // If a search pattern is specified, load the posts that match. if (!empty($q['s'])) { $search = $this->parse_search($q); } /** * Filter the search query. * * @param string $search Search filter for ES query. * @param ES_WP_Query $this The current ES_WP_Query object. */ if (!empty($search)) { $query['must'] = apply_filters_ref_array('es_posts_search', array($search, &$this)); if (!is_user_logged_in()) { $filter[] = array('or' => array($this->dsl_terms($this->es_map('post_password'), ''), $this->dsl_missing($this->es_map('post_password')))); } } // Taxonomies if (!$this->is_singular) { $this->parse_tax_query($q); $this->tax_query = new ES_WP_Tax_Query($this->tax_query); $tax_filter = $this->tax_query->get_dsl($this); if (false === $tax_filter) { return $this->no_results(); } if (!empty($tax_filter)) { $filter[] = $tax_filter; } unset($tax_filter); } if ($this->is_tax) { if (empty($post_type)) { // Do a fully inclusive search for currently registered post types of queried taxonomies $post_type = array(); $taxonomies = wp_list_pluck($this->tax_query->queries, 'taxonomy'); foreach (get_post_types(array('exclude_from_search' => false)) as $pt) { $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies($pt); if (array_intersect($taxonomies, $object_taxonomies)) { $post_type[] = $pt; } } if (!$post_type) { $post_type = 'any'; } elseif (count($post_type) == 1) { $post_type = $post_type[0]; } // @todo: no good way to do this in ES; workarounds? $post_status_join = true; } elseif (in_array('attachment', (array) $post_type)) { // @todo: no good way to do this in ES; workarounds? $post_status_join = true; } } // Back-compat if (!empty($this->tax_query->queries)) { $tax_query_in_and = wp_list_filter($this->tax_query->queries, array('operator' => 'NOT IN'), 'NOT'); if (!empty($tax_query_in_and)) { if (!isset($q['taxonomy'])) { foreach ($tax_query_in_and as $a_tax_query) { if (!in_array($a_tax_query['taxonomy'], array('category', 'post_tag'))) { $q['taxonomy'] = $a_tax_query['taxonomy']; if ('slug' == $a_tax_query['field']) { $q['term'] = $a_tax_query['terms'][0]; } else { $q['term_id'] = $a_tax_query['terms'][0]; } break; } } } $cat_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'category')); if (!empty($cat_query)) { $cat_query = reset($cat_query); if (!empty($cat_query['terms'][0])) { $the_cat = get_term_by($cat_query['field'], $cat_query['terms'][0], 'category'); if ($the_cat) { $this->set('cat', $the_cat->term_id); $this->set('category_name', $the_cat->slug); } unset($the_cat); } } unset($cat_query); $tag_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'post_tag')); if (!empty($tag_query)) { $tag_query = reset($tag_query); if (!empty($tag_query['terms'][0])) { $the_tag = get_term_by($tag_query['field'], $tag_query['terms'][0], 'post_tag'); if ($the_tag) { $this->set('tag_id', $the_tag->term_id); } unset($the_tag); } } unset($tag_query); } } // @todo: hmmmm if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) { $groupby = "{$wpdb->posts}.ID"; } // Author/user stuff if (!empty($q['author']) && $q['author'] != '0') { $q['author'] = addslashes_gpc('' . urldecode($q['author'])); $authors = array_unique(array_map('intval', preg_split('/[,\\s]+/', $q['author']))); foreach ($authors as $author) { $key = $author > 0 ? 'author__in' : 'author__not_in'; $q[$key][] = abs($author); } $q['author'] = implode(',', $authors); } if (!empty($q['author__not_in'])) { $author__not_in = array_map('absint', array_unique((array) $q['author__not_in'])); $filter[] = array('not' => $this->dsl_terms($this->es_map('post_author'), $author__not_in)); } elseif (!empty($q['author__in'])) { $author__in = array_map('absint', array_unique((array) $q['author__in'])); $filter[] = $this->dsl_terms($this->es_map('post_author'), $author__in); } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query($q['author_name']); $filter[] = $this->dsl_terms($this->es_map('post_author.user_nicename'), $q['author_name']); } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $es_mime = $this->post_mime_type_query($q['post_mime_type'], $wpdb->posts); if (!empty($es_mime['filters'])) { $filter[] = $es_mime['filters']; } if (!empty($es_mime['query'])) { if (empty($query['should'])) { $query['should'] = $es_mime['query']; } else { $query['should'] = array_merge($query['should'], $es_mime['query']); } } } if (!isset($q['order'])) { $q['order'] = 'desc'; } else { $q['order'] = $this->parse_order($q['order']); } // Order by if (empty($q['orderby'])) { /* * Boolean false or empty array blanks out ORDER BY, * while leaving the value unset or otherwise empty sets the default. */ if (isset($q['orderby']) && (is_array($q['orderby']) || false === $q['orderby'])) { $orderby = ''; } else { $sort[] = array($this->es_map('post_date') => $q['order']); } } elseif ('none' == $q['orderby']) { // nothing to see here } elseif ($q['orderby'] == 'post__in' && !empty($post__in)) { // @todo: Figure this out... Elasticsearch doesn't have an equivalent of this // $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )"; } elseif ($q['orderby'] == 'post_parent__in' && !empty($post_parent__in)) { // (see above) // $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )"; } else { if (is_array($q['orderby'])) { foreach ($q['orderby'] as $_orderby => $order) { $orderby = addslashes_gpc(urldecode($_orderby)); $parsed = $this->parse_orderby($orderby); if (!$parsed) { continue; } $sort[] = array($parsed => $this->parse_order($order)); } } else { $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); foreach (explode(' ', $q['orderby']) as $i => $orderby) { $parsed = $this->parse_orderby($orderby); // Only allow certain values for safety. if (!$parsed) { continue; } $sort[] = array($parsed => $q['order']); } if (empty($sort)) { $sort[] = array($this->es_map('post_date') => $q['order']); } } } // Order search results by relevance only when another "orderby" is not specified in the query. if (!empty($q['s'])) { $search_orderby = array(); if (empty($q['orderby']) && !$this->is_feed || isset($q['orderby']) && 'relevance' === $q['orderby']) { $search_orderby = array('_score'); } /** * Filter the order used when ordering search results. * * @param array $search_orderby The order clause. * @param ES_WP_Query $this The current ES_WP_Query instance. */ $search_orderby = apply_filters('es_posts_search_orderby', $search_orderby, $this); if ($search_orderby) { $sort = $sort ? array_merge($search_orderby, $sort) : $search_orderby; } } if (is_array($post_type) && count($post_type) > 1) { $post_type_cap = 'multiple_post_type'; } else { if (is_array($post_type)) { $post_type = reset($post_type); } $post_type_object = get_post_type_object($post_type); if (empty($post_type_object)) { $post_type_cap = $post_type; } } if ('any' == $post_type) { $in_search_post_types = get_post_types(array('exclude_from_search' => false)); if (empty($in_search_post_types)) { // @todo: potentially do this differently; see no_results() for more info return $this->no_results(); } else { $filter[] = $this->dsl_terms($this->es_map('post_type'), array_values($in_search_post_types)); } } elseif (!empty($post_type)) { $filter[] = $this->dsl_terms($this->es_map('post_type'), array_values((array) $post_type)); if (!is_array($post_type)) { $post_type_object = get_post_type_object($post_type); } } elseif ($this->is_attachment) { $filter[] = $this->dsl_terms($this->es_map('post_type'), 'attachment'); $post_type_object = get_post_type_object('attachment'); } elseif ($this->is_page) { $filter[] = $this->dsl_terms($this->es_map('post_type'), 'page'); $post_type_object = get_post_type_object('page'); } else { $filter[] = $this->dsl_terms($this->es_map('post_type'), 'post'); $post_type_object = get_post_type_object('post'); } $edit_cap = 'edit_post'; $read_cap = 'read_post'; if (!empty($post_type_object)) { $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } $user_id = get_current_user_id(); if (!empty($q['post_status'])) { $statuswheres = array(); $q_status = $q['post_status']; if (!is_array($q_status)) { $q_status = explode(',', $q_status); } $r_status = array(); $p_status = array(); $e_status = array(); if (in_array('any', $q_status)) { $e_status = get_post_stati(array('exclude_from_search' => true)); $e_status = array_values($e_status); } else { foreach (get_post_stati() as $status) { if (in_array($status, $q_status)) { if ('private' == $status) { $p_status[] = $status; } else { $r_status[] = $status; } } } } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($e_status)) { // $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")"; $status_ands[] = array('not' => $this->dsl_terms($this->es_map('post_status'), $e_status)); } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) { // $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))"; $status_ands[] = array('bool' => array('must' => array($this->dsl_terms($this->es_map('post_author'), $user_id), $this->dsl_terms($this->es_map('post_status'), $r_status)))); } else { // $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")"; $status_ands[] = $this->dsl_terms($this->es_map('post_status'), $r_status); } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) { // $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))"; $status_ands[] = array('bool' => array('must' => array($this->dsl_terms($this->es_map('post_author'), $user_id), $this->dsl_terms($this->es_map('post_status'), $p_status)))); } else { // $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")"; $status_ands[] = $this->dsl_terms($this->es_map('post_status'), $p_status); } } if ($post_status_join) { // @todo: no good way to do this in ES... /* $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) "; foreach ( $statuswheres as $index => $statuswhere ) $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; */ } $filter = array_merge($filter, $status_ands); } elseif (!$this->is_singular) { $singular_states = array('publish'); // Add public states. $singular_states = array_merge($singular_states, (array) get_post_stati(array('public' => true))); if ($this->is_admin) { // Add protected states that should show in the admin all list. $singular_states = array_merge($singular_states, (array) get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true))); } if (is_user_logged_in()) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati(array('private' => true)); $singular_states_ors = array(); foreach ((array) $private_states as $state) { // @todo: leaving off here if (current_user_can($read_private_cap)) { $singular_states[] = $state; } else { $singular_states_ors[] = array('and' => array($this->dsl_terms($this->es_map('post_author'), $user_id), $this->dsl_terms($this->es_map('post_status'), $state))); } } } $singular_states = array_values(array_unique($singular_states)); $singular_states_filter = $this->dsl_terms($this->es_map('post_status'), $singular_states); if (!empty($singular_states_ors)) { $singular_states_ors[] = $singular_states_filter; $filter[] = array('or' => $singular_states_ors); } else { $filter[] = $singular_states_filter; } unset($singular_states, $singular_states_filter, $singular_states_ors, $private_states); } if (!empty($this->meta_query->queries)) { $filter[] = $this->meta_query->get_dsl($this, 'post'); } // Apply filters on the filter clause prior to paging so that any // manipulations to them are reflected in the paging by day queries. if (!$q['suppress_filters']) { $filter = apply_filters_ref_array('es_query_filter', array($filter, &$this)); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (!$page) { $page = 1; } if (empty($q['offset'])) { $from = ($page - 1) * $q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $from = absint($q['offset']); } $size = $q['posts_per_page']; } else { $from = $size = false; } // Comments feeds // @todo: come back to this if (0 && $this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) { if ($this->is_archive || $this->is_search) { $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "{$wpdb->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { $cjoin = apply_filters_ref_array('es_comment_feed_join', array($cjoin, &$this)); $cwhere = apply_filters_ref_array('es_comment_feed_where', array($cwhere, &$this)); $cgroupby = apply_filters_ref_array('es_comment_feed_groupby', array($cgroupby, &$this)); $corderby = apply_filters_ref_array('es_comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $climits = apply_filters_ref_array('es_comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); } $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } // Run cleanup on our filter and query $filter = array_filter($filter); if (!empty($filter)) { $filter = array('and' => $filter); } $query = array_filter($query); if (!empty($query)) { if (1 == count($query) && !empty($query['must']) && 1 == count($query['must'])) { $query = $query['must']; } else { $query = array('bool' => $query); if (!empty($query['bool']['should'])) { $query['bool']['minimum_should_match'] = 1; } } } $pieces = array('filter', 'query', 'sort', 'fields', 'size', 'from'); // Apply post-paging filters on our clauses. Only plugins that // manipulate paging queries should use these hooks. if (!$q['suppress_filters']) { $filter = apply_filters_ref_array('es_posts_filter_paged', array($filter, &$this)); $query = apply_filters_ref_array('es_posts_query_paged', array($query, &$this)); $sort = apply_filters_ref_array('es_posts_sort', array($sort, &$this)); $fields = apply_filters_ref_array('es_posts_fields', array($fields, &$this)); $size = apply_filters_ref_array('es_posts_size', array($size, &$this)); $from = apply_filters_ref_array('es_posts_from', array($from, &$this)); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array('es_posts_clauses', array(compact($pieces), &$this)); foreach ($pieces as $piece) { ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : ''; } } // Announce current selection parameters. For use by caching plugins. do_action('es_posts_selection', array('filter' => $filter, 'query' => $query, 'sort' => $sort, 'fields' => $fields, 'size' => $size, 'from' => $from)); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if (!$q['suppress_filters']) { $filter = apply_filters_ref_array('es_posts_filter_request', array($filter, &$this)); $query = apply_filters_ref_array('es_posts_query_request', array($query, &$this)); $sort = apply_filters_ref_array('es_posts_sort_request', array($sort, &$this)); $fields = apply_filters_ref_array('es_posts_fields_request', array($fields, &$this)); $size = apply_filters_ref_array('es_posts_size_request', array($size, &$this)); $from = apply_filters_ref_array('es_posts_from_request', array($from, &$this)); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array('es_posts_clauses_request', array(compact($pieces), &$this)); foreach ($pieces as $piece) { ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : ''; } } $this->es_args = array('filter' => $filter, 'query' => $query, 'sort' => $sort, 'fields' => $fields, 'from' => $from, 'size' => $size); // Remove empty criteria foreach ($this->es_args as $key => $value) { if (empty($value) && 0 !== $value) { unset($this->es_args[$key]); } } // Elasticsearch needs a size, so we set it very high if posts_per_page = -1 if (-1 == $q['posts_per_page'] && !isset($this->es_args['size'])) { $this->es_args['size'] = $size = apply_filters('es_query_max_results', 1000); } $old_args = $this->es_args; if (!$q['suppress_filters']) { $this->es_args = apply_filters_ref_array('es_posts_request', array($this->es_args, &$this)); } if ('ids' == $q['fields'] || 'id=>parent' == $q['fields']) { $this->es_response = $this->query_es($this->es_args); $this->set_posts($q, $this->es_response); $this->post_count = count($this->posts); $this->set_found_posts($q, $this->es_response); return $this->posts; } $this->es_response = $this->query_es($this->es_args); $this->set_posts($q, $this->es_response); $this->set_found_posts($q, $this->es_response); // The rest of this method is mostly core // Convert to WP_Post objects if ($this->posts) { $this->posts = array_map('get_post', $this->posts); } // Raw results filter. Prior to status checks. if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('es_posts_results', array($this->posts, &$this)); } // @todo: address this if (0 && !empty($this->posts) && $this->is_comment_feed && $this->is_singular) { $cjoin = apply_filters_ref_array('es_comment_feed_join', array('', &$this)); $cwhere = apply_filters_ref_array('es_comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this)); $cgroupby = apply_filters_ref_array('es_comment_feed_groupby', array('', &$this)); $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = apply_filters_ref_array('es_comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $climits = apply_filters_ref_array('es_comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"; $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); $post_status_obj = get_post_status_object($status); //$type = get_post_type($this->posts[0]); if (!$post_status_obj->public) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ($post_status_obj->protected) { // User must have edit permissions on the draft to preview. if (!current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; if ('future' != $status) { $this->posts[0]->post_date = current_time('mysql'); } } } elseif ($post_status_obj->private) { if (!current_user_can($read_cap, $this->posts[0]->ID)) { $this->posts = array(); } } else { $this->posts = array(); } } } if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts[0] = get_post(apply_filters_ref_array('es_the_preview', array($this->posts[0], &$this))); } } // @todo: address this // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if (0 && $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset($sticky_posts[$offset]); } } // If any posts have been excluded specifically, Ignore those that are sticky. if (!empty($sticky_posts) && !empty($q['post__not_in'])) { $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies = get_posts(array('post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true)); foreach ($stickies as $sticky_post) { array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('es_the_posts', array($this->posts, &$this)); } // Ensure that any posts added/modified via one of the filters above are // of the type WP_Post and are filtered. if ($this->posts) { $this->post_count = count($this->posts); $this->posts = array_map('get_post', $this->posts); if ($q['cache_results']) { update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); } $this->post = reset($this->posts); } else { $this->post_count = 0; $this->posts = array(); } return $this->posts; }
</div> </div> <?php if (!function_exists('dynamic_sidebar') || !dynamic_sidebar('Advert_3')) { if (function_exists(displaySubtleAds)) { displaySubtleAds(3); } } ?> <br class="clear" /> <?php $post = $temp_post; update_post_caches($post_id); comments_template(); ?> <?php } } else { ?> <p><?php _e("Sorry, no posts matched your criteria.", 'gluedideas_subtle'); ?> </p> <?php }
/** * Adds any posts from the given ids to the cache that do not already exist in cache * * @since 3.4.0 * @access private * * @see update_post_caches() * * @global wpdb $wpdb WordPress database abstraction object. * * @param array $ids ID list. * @param bool $update_term_cache Optional. Whether to update the term cache. Default true. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true. */ function _prime_post_caches($ids, $update_term_cache = true, $update_meta_cache = true) { global $wpdb; $non_cached_ids = _get_non_cached_ids($ids, 'posts'); if (!empty($non_cached_ids)) { $fresh_posts = $wpdb->get_results(sprintf("SELECT {$wpdb->posts}.* FROM {$wpdb->posts} WHERE ID IN (%s)", join(",", $non_cached_ids))); update_post_caches($fresh_posts, 'any', $update_term_cache, $update_meta_cache); } }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @return array List of posts. */ function &get_posts() { global $wpdb, $user_ID, $_wp_using_ext_object_cache; $this->parse_query(); do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars($q); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5(serialize($this->query_vars)); if ($hash != $this->query_vars_hash) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $fields = ''; $post_status_join = false; $page = 1; if (isset($q['caller_get_posts'])) { _deprecated_argument('WP_Query', '3.1', __('"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.')); if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = $q['caller_get_posts']; } } if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['cache_results'])) { if ($_wp_using_ext_object_cache) { $q['cache_results'] = false; } else { $q['cache_results'] = true; } } if (!isset($q['update_post_term_cache'])) { $q['update_post_term_cache'] = true; } if (!isset($q['update_post_meta_cache'])) { $q['update_post_meta_cache'] = true; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = ''; } } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present. if (isset($q['no_found_rows'])) { $q['no_found_rows'] = (bool) $q['no_found_rows']; } else { $q['no_found_rows'] = false; } switch ($q['fields']) { case 'ids': $fields = "{$wpdb->posts}.ID"; break; case 'id=>parent': $fields = "{$wpdb->posts}.ID, {$wpdb->posts}.post_parent"; break; default: $fields = "{$wpdb->posts}.*"; } // If a month is specified in the querystring, load that month if ($q['m']) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2); } } if ('' !== $q['hour']) { $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'"; } if ('' !== $q['minute']) { $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'"; } if ('' !== $q['second']) { $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'"; } if ($q['year']) { $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'"; } if ($q['monthnum']) { $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'"; } if ($q['day']) { $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'"; } // If we've got a post_type AND its not "any" post_type. if (!empty($q['post_type']) && 'any' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) { continue; } if (!$ptype_obj->hierarchical || strpos($q[$ptype_obj->query_var], '/') === false) { // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name' $q['name'] = $q[$ptype_obj->query_var]; } else { // Hierarchical post_types will operate through the $q['pagename'] = $q[$ptype_obj->query_var]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ('' != $q['name']) { $q['name'] = sanitize_title_for_query($q['name']); $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'"; } elseif ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { if ('page' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->hierarchical) { continue; } $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ($reqpage) { break; } } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename'])); $q['name'] = $q['pagename']; $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')"; $reqpage_obj = get_page($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment'])); $q['name'] = $q['attachment']; $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'"; } if ($q['w']) { $where .= ' AND ' . _wp_mysql_week("`{$wpdb->posts}`.`post_date`") . " = '" . $q['w'] . "'"; } if (intval($q['comments_popup'])) { $q['p'] = absint($q['comments_popup']); } // If an attachment is requested by number, let it supersede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $where .= " AND {$wpdb->posts}.ID = " . $q['p']; } elseif ($q['post__in']) { $post__in = implode(',', array_map('absint', $q['post__in'])); $where .= " AND {$wpdb->posts}.ID IN ({$post__in})"; } elseif ($q['post__not_in']) { $post__not_in = implode(',', array_map('absint', $q['post__not_in'])); $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})"; } if (is_numeric($q['post_parent'])) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']); } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $where = " AND {$wpdb->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { // added slashes screw with quote grouping when done early, so done later $q['s'] = stripslashes($q['s']); if (!empty($q['sentence'])) { $q['search_terms'] = array($q['s']); } else { preg_match_all('/".*?("|$)|((?<=[\\r\\n\\t ",+])|^)[^\\r\\n\\t ",+]+/', $q['s'], $matches); $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]); } $n = !empty($q['exact']) ? '' : '%'; $searchand = ''; foreach ((array) $q['search_terms'] as $term) { $term = esc_sql(like_escape($term)); $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))"; $searchand = ' AND '; } if (!empty($search)) { $search = " AND ({$search}) "; if (!is_user_logged_in()) { $search .= " AND ({$wpdb->posts}.post_password = '') "; } } } // Allow plugins to contextually add/remove/modify the search section of the database query $search = apply_filters_ref_array('posts_search', array($search, &$this)); // Taxonomies if (!$this->is_singular) { $this->parse_tax_query($q); $clauses = $this->tax_query->get_sql($wpdb->posts, 'ID'); $join .= $clauses['join']; $where .= $clauses['where']; } if ($this->is_tax) { if (empty($post_type)) { $post_type = 'any'; $post_status_join = true; } elseif (in_array('attachment', (array) $post_type)) { $post_status_join = true; } } // Back-compat if (!empty($this->tax_query->queries)) { $tax_query_in_and = wp_list_filter($this->tax_query->queries, array('operator' => 'NOT IN'), 'NOT'); if (!empty($tax_query_in_and)) { if (!isset($q['taxonomy'])) { foreach ($tax_query_in_and as $a_tax_query) { if (!in_array($a_tax_query['taxonomy'], array('category', 'post_tag'))) { $q['taxonomy'] = $a_tax_query['taxonomy']; if ('slug' == $a_tax_query['field']) { $q['term'] = $a_tax_query['terms'][0]; } else { $q['term_id'] = $a_tax_query['terms'][0]; } break; } } } $cat_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'category')); if (!empty($cat_query)) { $cat_query = reset($cat_query); $the_cat = get_term_by($cat_query['field'], $cat_query['terms'][0], 'category'); if ($the_cat) { $this->set('cat', $the_cat->term_id); $this->set('category_name', $the_cat->slug); } unset($the_cat); } unset($cat_query); $tag_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'post_tag')); if (!empty($tag_query)) { $tag_query = reset($tag_query); $the_tag = get_term_by($tag_query['field'], $tag_query['terms'][0], 'post_tag'); if ($the_tag) { $this->set('tag_id', $the_tag->term_id); } unset($the_tag); } unset($tag_query); } } if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) { $groupby = "{$wpdb->posts}.ID"; } // Author/user stuff if (empty($q['author']) || $q['author'] == '0') { $whichauthor = ''; } else { $q['author'] = (string) urldecode($q['author']); $q['author'] = addslashes_gpc($q['author']); if (strpos($q['author'], '-') !== false) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = (string) absint($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\\s]+/', $q['author']); $_author_array = array(); foreach ($author_array as $key => $_author) { $_author_array[] = "{$wpdb->posts}.post_author " . $eq . ' ' . absint($_author); } $whichauthor .= ' AND (' . implode(" {$andor} ", $_author_array) . ')'; unset($author_array, $_author_array); } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query($q['author_name']); $q['author'] = get_user_by('slug', $q['author_name']); if ($q['author']) { $q['author'] = $q['author']->ID; } $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $wpdb->posts); } $where .= $search . $whichauthor . $whichmimetype; if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') { $q['order'] = 'DESC'; } // Order by if (empty($q['orderby'])) { $orderby = "{$wpdb->posts}.post_date " . $q['order']; } elseif ('none' == $q['orderby']) { $orderby = ''; } else { // Used to filter values $allowed_keys = array('name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count'); if (!empty($q['meta_key'])) { $allowed_keys[] = $q['meta_key']; $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; } $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = array(); foreach (explode(' ', $q['orderby']) as $i => $orderby) { // Only allow certain values for safety if (!in_array($orderby, $allowed_keys)) { continue; } switch ($orderby) { case 'menu_order': break; case 'ID': $orderby = "{$wpdb->posts}.ID"; break; case 'rand': $orderby = 'RAND()'; break; case $q['meta_key']: case 'meta_value': $orderby = "{$wpdb->postmeta}.meta_value"; break; case 'meta_value_num': $orderby = "{$wpdb->postmeta}.meta_value+0"; break; case 'comment_count': $orderby = "{$wpdb->posts}.comment_count"; break; default: $orderby = "{$wpdb->posts}.post_" . $orderby; } $orderby_array[] = $orderby; } $orderby = implode(',', $orderby_array); if (empty($orderby)) { $orderby = "{$wpdb->posts}.post_date " . $q['order']; } else { $orderby .= " {$q['order']}"; } } if (is_array($post_type)) { $post_type_cap = 'multiple_post_type'; } else { $post_type_object = get_post_type_object($post_type); if (empty($post_type_object)) { $post_type_cap = $post_type; } } if ('any' == $post_type) { $in_search_post_types = get_post_types(array('exclude_from_search' => false)); if (!empty($in_search_post_types)) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')"); } } elseif (!empty($post_type) && is_array($post_type)) { $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", $post_type) . "')"; } elseif (!empty($post_type)) { $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'"; $post_type_object = get_post_type_object($post_type); } elseif ($this->is_attachment) { $where .= " AND {$wpdb->posts}.post_type = 'attachment'"; $post_type_object = get_post_type_object('attachment'); } elseif ($this->is_page) { $where .= " AND {$wpdb->posts}.post_type = 'page'"; $post_type_object = get_post_type_object('page'); } else { $where .= " AND {$wpdb->posts}.post_type = 'post'"; $post_type_object = get_post_type_object('post'); } if (!empty($post_type_object)) { $edit_cap = $post_type_object->cap->edit_post; $read_cap = $post_type_object->cap->read_post; $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_cap = 'edit_' . $post_type_cap; $read_cap = 'read_' . $post_type_cap; $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } if (!empty($q['post_status'])) { $statuswheres = array(); $q_status = $q['post_status']; if (!is_array($q_status)) { $q_status = explode(',', $q_status); } $r_status = array(); $p_status = array(); $e_status = array(); if (in_array('any', $q_status)) { foreach (get_post_stati(array('exclude_from_search' => true)) as $status) { $e_status[] = "{$wpdb->posts}.post_status <> '{$status}'"; } } else { foreach (get_post_stati() as $status) { if (in_array($status, $q_status)) { if ('private' == $status) { $p_status[] = "{$wpdb->posts}.post_status = '{$status}'"; } else { $r_status[] = "{$wpdb->posts}.post_status = '{$status}'"; } } } } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($e_status)) { $statuswheres[] = "(" . join(' AND ', $e_status) . ")"; } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) { $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $r_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $r_status) . ")"; } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) { $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $p_status) . ")"; } } if ($post_status_join) { $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) "; foreach ($statuswheres as $index => $statuswhere) { $statuswheres[$index] = "({$statuswhere} OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; } } foreach ($statuswheres as $statuswhere) { $where .= " AND {$statuswhere}"; } } elseif (!$this->is_singular) { $where .= " AND ({$wpdb->posts}.post_status = 'publish'"; // Add public states. $public_states = get_post_stati(array('public' => true)); foreach ((array) $public_states as $state) { if ('publish' == $state) { // Publish is hard-coded above. continue; } $where .= " OR {$wpdb->posts}.post_status = '{$state}'"; } if ($this->is_admin) { // Add protected states that should show in the admin all list. $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true)); foreach ((array) $admin_all_states as $state) { $where .= " OR {$wpdb->posts}.post_status = '{$state}'"; } } if (is_user_logged_in()) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati(array('private' => true)); foreach ((array) $private_states as $state) { $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}'"; } } $where .= ')'; } if (!empty($this->meta_query->queries)) { $clauses = $this->meta_query->get_sql('post', $wpdb->posts, 'ID', $this); $join .= $clauses['join']; $where .= $clauses['where']; } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. if (!$q['suppress_filters']) { $where = apply_filters_ref_array('posts_where', array($where, &$this)); $join = apply_filters_ref_array('posts_join', array($join, &$this)); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (!$page) { $page = 1; } if (empty($q['offset'])) { $pgstrt = ($page - 1) * $q['posts_per_page'] . ', '; } else { // we're ignoring $page and using 'offset' $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; } $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } // Comments feeds if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) { if ($this->is_archive || $this->is_search) { $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "{$wpdb->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this)); $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this)); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this)); $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); } $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } $pieces = array('where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits'); // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. if (!$q['suppress_filters']) { $where = apply_filters_ref_array('posts_where_paged', array($where, &$this)); $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this)); $join = apply_filters_ref_array('posts_join_paged', array($join, &$this)); $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this)); $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this)); $limits = apply_filters_ref_array('post_limits', array($limits, &$this)); $fields = apply_filters_ref_array('posts_fields', array($fields, &$this)); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array('posts_clauses', array(compact($pieces), &$this)); foreach ($pieces as $piece) { ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : ''; } } // Announce current selection parameters. For use by caching plugins. do_action('posts_selection', $where . $groupby . $orderby . $limits . $join); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if (!$q['suppress_filters']) { $where = apply_filters_ref_array('posts_where_request', array($where, &$this)); $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this)); $join = apply_filters_ref_array('posts_join_request', array($join, &$this)); $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this)); $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this)); $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this)); $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this)); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array('posts_clauses_request', array(compact($pieces), &$this)); foreach ($pieces as $piece) { ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : ''; } } if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } if (!empty($orderby)) { $orderby = 'ORDER BY ' . $orderby; } $found_rows = ''; if (!$q['no_found_rows'] && !empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->request = $old_request = "SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; if (!$q['suppress_filters']) { $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this)); } if ('ids' == $q['fields']) { $this->posts = $wpdb->get_col($this->request); return $this->posts; } if ('id=>parent' == $q['fields']) { $this->posts = $wpdb->get_results($this->request); $r = array(); foreach ($this->posts as $post) { $r[$post->ID] = $post->post_parent; } return $r; } if ($old_request == $this->request && "{$wpdb->posts}.*" == $fields) { // First get the IDs and then fill in the objects $this->request = "SELECT {$found_rows} {$distinct} {$wpdb->posts}.ID FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; $this->request = apply_filters('posts_request_ids', $this->request, $this); $ids = $wpdb->get_col($this->request); if ($ids) { $this->set_found_posts($q, $limits); _prime_post_caches($ids, $q['update_post_term_cache'], $q['update_post_meta_cache']); $this->posts = array_map('get_post', $ids); } else { $this->found_posts = $this->max_num_pages = 0; $this->posts = array(); } } else { $this->posts = $wpdb->get_results($this->request); $this->set_found_posts($q, $limits); } // Raw results filter. Prior to status checks. if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this)); } if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) { $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this)); $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this)); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this)); $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"; $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]->ID); $post_status_obj = get_post_status_object($status); //$type = get_post_type($this->posts[0]); if (!$post_status_obj->public) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ($post_status_obj->protected) { // User must have edit permissions on the draft to preview. if (!current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; if ('future' != $status) { $this->posts[0]->post_date = current_time('mysql'); } } } elseif ($post_status_obj->private) { if (!current_user_can($read_cap, $this->posts[0]->ID)) { $this->posts = array(); } } else { $this->posts = array(); } } } if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts[0] = apply_filters_ref_array('the_preview', array($this->posts[0], &$this)); } } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset($sticky_posts[$offset]); } } // If any posts have been excluded specifically, Ignore those that are sticky. if (!empty($sticky_posts) && !empty($q['post__not_in'])) { $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies__in = implode(',', array_map('absint', $sticky_posts)); // honor post type(s) if not set to any $stickies_where = ''; if ('any' != $post_type && '' != $post_type) { if (is_array($post_type)) { $post_types = join("', '", $post_type); } else { $post_types = $post_type; } $stickies_where = "AND {$wpdb->posts}.post_type IN ('" . $post_types . "')"; } $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in}) {$stickies_where}"); foreach ($stickies as $sticky_post) { // Ignore sticky posts the current user cannot read or are not published. if ('publish' != $sticky_post->post_status) { continue; } array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this)); } $this->post_count = count($this->posts); // Always sanitize foreach ($this->posts as $i => $post) { $this->posts[$i] = sanitize_post($post, 'raw'); } if ($q['cache_results']) { update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); } if ($this->post_count > 0) { $this->post = $this->posts[0]; } return $this->posts; }
/** * get_posts() - Returns a number of posts * * {@internal Missing Long Description}} * * @package WordPress * @subpackage Post * @since 1.2 * @uses $wpdb * * @param array $args {@internal Missing Description}} * @return array {@internal Missing Description}} */ function get_posts($args = null) { global $wpdb; $defaults = array('numberposts' => 5, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'post', 'post_status' => 'publish', 'post_parent' => 0); $r = wp_parse_args($args, $defaults); extract($r, EXTR_SKIP); $numberposts = (int) $numberposts; $offset = (int) $offset; $category = (int) $category; $post_parent = (int) $post_parent; $inclusions = ''; if (!empty($include)) { $offset = 0; //ignore offset, category, exclude, meta_key, and meta_value, post_parent if using include $category = 0; $exclude = ''; $meta_key = ''; $meta_value = ''; $post_parent = 0; $incposts = preg_split('/[\\s,]+/', $include); $numberposts = count($incposts); // only the number of posts included if (count($incposts)) { foreach ($incposts as $incpost) { if (empty($inclusions)) { $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpost); } else { $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpost); } } } } if (!empty($inclusions)) { $inclusions .= ')'; } $exclusions = ''; if (!empty($exclude)) { $exposts = preg_split('/[\\s,]+/', $exclude); if (count($exposts)) { foreach ($exposts as $expost) { if (empty($exclusions)) { $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expost); } else { $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expost); } } } } if (!empty($exclusions)) { $exclusions .= ')'; } // orderby if (preg_match('/.+ +(ASC|DESC)/i', $orderby)) { $order = ''; } // orderby has its own order, so we'll use that $query = "SELECT DISTINCT * FROM {$wpdb->posts} "; $query .= empty($category) ? '' : ", {$wpdb->term_relationships}, {$wpdb->term_taxonomy} "; $query .= empty($meta_key) ? '' : ", {$wpdb->postmeta} "; $query .= " WHERE 1=1 "; $query .= empty($post_type) ? '' : $wpdb->prepare("AND post_type = %s ", $post_type); $query .= empty($post_status) ? '' : $wpdb->prepare("AND post_status = %s ", $post_status); $query .= "{$exclusions} {$inclusions} "; $query .= empty($category) ? '' : $wpdb->prepare("AND ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id AND {$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id AND {$wpdb->term_taxonomy}.term_id = %d AND {$wpdb->term_taxonomy}.taxonomy = 'category')", $category); $query .= empty($post_parent) ? '' : $wpdb->prepare("AND {$wpdb->posts}.post_parent = %d ", $post_parent); // expected_slashed ($meta_key, $meta_value) -- Also, this looks really funky, doesn't seem like it works $query .= empty($meta_key) | empty($meta_value) ? '' : " AND ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '{$meta_key}' AND {$wpdb->postmeta}.meta_value = '{$meta_value}' )"; $query .= empty($post_mime_type) ? '' : wp_post_mime_type_where($post_mime_type); $query .= " GROUP BY {$wpdb->posts}.ID ORDER BY " . $orderby . ' ' . $order; if (0 < $numberposts) { $query .= $wpdb->prepare(" LIMIT %d,%d", $offset, $numberposts); } $posts = $wpdb->get_results($query); update_post_caches($posts); return $posts; }
function &get_posts() { global $wpdb, $pagenow, $user_ID; do_action('pre_get_posts', array(&$this)); // Shorthand. $q = $this->query_vars; // First let's clear some variables $whichcat = ''; $whichauthor = ''; $whichpage = ''; $result = ''; $where = ''; $limits = ''; $distinct = ''; $join = ''; if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 ) $q['posts_per_page'] = get_settings('posts_per_page'); if ( !isset($q['what_to_show']) ) $q['what_to_show'] = get_settings('what_to_show'); if ( isset($q['showposts']) && $q['showposts'] ) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) ) $q['posts_per_page'] = $q['posts_per_archive_page']; if ( !isset($q['nopaging']) ) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ( $this->is_feed ) { $q['posts_per_page'] = get_settings('posts_per_rss'); $q['what_to_show'] = 'posts'; } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = (int) $q['page']; $q['page'] = abs($q['page']); } $add_hours = intval(get_settings('gmt_offset')); $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours)); $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"; // If a month is specified in the querystring, load that month if ( (int) $q['m'] ) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4); if (strlen($q['m'])>5) $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2); if (strlen($q['m'])>7) $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2); if (strlen($q['m'])>9) $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2); if (strlen($q['m'])>11) $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2); if (strlen($q['m'])>13) $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2); } if ( (int) $q['hour'] ) { $q['hour'] = '' . intval($q['hour']); $where .= " AND HOUR(post_date)='" . $q['hour'] . "'"; } if ( (int) $q['minute'] ) { $q['minute'] = '' . intval($q['minute']); $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'"; } if ( (int) $q['second'] ) { $q['second'] = '' . intval($q['second']); $where .= " AND SECOND(post_date)='" . $q['second'] . "'"; } if ( (int) $q['year'] ) { $q['year'] = '' . intval($q['year']); $where .= " AND YEAR(post_date)='" . $q['year'] . "'"; } if ( (int) $q['monthnum'] ) { $q['monthnum'] = '' . intval($q['monthnum']); $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'"; } if ( (int) $q['day'] ) { $q['day'] = '' . intval($q['day']); $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'"; } // Compat. Map subpost to attachment. if ( '' != $q['subpost'] ) $q['attachment'] = $q['subpost']; if ( '' != $q['subpost_id'] ) $q['attachment_id'] = $q['subpost_id']; if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND post_name = '" . $q['name'] . "'"; } else if ('' != $q['pagename']) { $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename']))); $page_paths = '/' . trim($q['pagename'], '/'); $q['pagename'] = sanitize_title(basename($page_paths)); $q['name'] = $q['pagename']; $page_paths = explode('/', $page_paths); foreach($page_paths as $pathdir) $page_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); $all_page_ids = get_all_page_ids(); $reqpage = 0; if (is_array($all_page_ids)) { foreach ( $all_page_ids as $page_id ) { $page = get_page($page_id); if ( $page->fullpath == $page_path ) { $reqpage = $page_id; break; } } } $where .= " AND (ID = '$reqpage')"; } elseif ('' != $q['attachment']) { $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment']))); $attach_paths = '/' . trim($q['attachment'], '/'); $q['attachment'] = sanitize_title(basename($attach_paths)); $q['name'] = $q['attachment']; $where .= " AND post_name = '" . $q['attachment'] . "'"; } if ( (int) $q['w'] ) { $q['w'] = ''.intval($q['w']); $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'"; } if ( intval($q['comments_popup']) ) $q['p'] = intval($q['comments_popup']); // If a attachment is requested by number, let it supercede any post number. if ( ($q['attachment_id'] != '') && (intval($q['attachment_id']) != 0) ) $q['p'] = (int) $q['attachment_id']; // If a post number is specified, load that post if (($q['p'] != '') && intval($q['p']) != 0) { $q['p'] = (int) $q['p']; $where = ' AND ID = ' . $q['p']; } if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) { $q['page_id'] = intval($q['page_id']); $q['p'] = $q['page_id']; $where = ' AND ID = '.$q['page_id']; } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { $q['s'] = addslashes_gpc($q['s']); $search = ' AND ('; $q['s'] = preg_replace('/, +/', ' ', $q['s']); $q['s'] = str_replace(',', ' ', $q['s']); $q['s'] = str_replace('"', ' ', $q['s']); $q['s'] = trim($q['s']); if ($q['exact']) { $n = ''; } else { $n = '%'; } if (!$q['sentence']) { $s_array = explode(' ',$q['s']); $q['search_terms'] = $s_array; $search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))'; for ( $i = 1; $i < count($s_array); $i = $i + 1) { $search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))'; } $search .= ' OR (post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\')'; $search .= ')'; } else { $search = ' AND ((post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\'))'; } } // Category stuff if ((empty($q['cat'])) || ($q['cat'] == '0') || // Bypass cat checks if fetching specific posts ( $this->is_single || $this->is_page )) { $whichcat=''; } else { $q['cat'] = ''.urldecode($q['cat']).''; $q['cat'] = addslashes_gpc($q['cat']); if (stristr($q['cat'],'-')) { // Note: if we have a negative, we ignore all the positives. It must // always mean 'everything /except/ this one'. We should be able to do // multiple negatives but we don't :-( $eq = '!='; $andor = 'AND'; $q['cat'] = explode('-',$q['cat']); $q['cat'] = intval($q['cat'][1]); } else { $eq = '='; $andor = 'OR'; } $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) "; $cat_array = preg_split('/[,\s]+/', $q['cat']); $whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]); $whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' '); for ($i = 1; $i < (count($cat_array)); $i = $i + 1) { $whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]); $whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' '); } $whichcat .= ')'; if ($eq == '!=') { $q['cat'] = '-'.$q['cat']; // Put back the knowledge that we are excluding a category. } } // Category stuff for nice URIs global $cache_categories; if ('' != $q['category_name']) { $cat_paths = '/' . trim(urldecode($q['category_name']), '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = explode('/', $cat_paths); foreach($cat_paths as $pathdir) $cat_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); $all_cat_ids = get_all_category_ids(); $q['cat'] = 0; $partial_match = 0; foreach ( $all_cat_ids as $cat_id ) { $cat = get_category($cat_id); if ( $cat->fullpath == $cat_path ) { $q['cat'] = $cat_id; break; } elseif ( $cat->category_nicename == $q['category_name'] ) { $partial_match = $cat_id; } } //if we don't match the entire hierarchy fallback on just matching the nicename if (!$q['cat'] && $partial_match) { $q['cat'] = $partial_match; } $tables = ", $wpdb->post2cat, $wpdb->categories"; $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) LEFT JOIN $wpdb->categories ON ($wpdb->post2cat.category_id = $wpdb->categories.cat_ID) "; $whichcat = " AND (category_id = '" . $q['cat'] . "'"; $whichcat .= get_category_children($q['cat'], " OR category_id = "); $whichcat .= ")"; } // Author/user stuff if ((empty($q['author'])) || ($q['author'] == '0')) { $whichauthor=''; } else { $q['author'] = ''.urldecode($q['author']).''; $q['author'] = addslashes_gpc($q['author']); if (stristr($q['author'], '-')) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = ''.intval($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\s]+/', $q['author']); $whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]); for ($i = 1; $i < (count($author_array)); $i = $i + 1) { $whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]); } $whichauthor .= ')'; } // Author stuff for nice URIs if ('' != $q['author_name']) { if (stristr($q['author_name'],'/')) { $q['author_name'] = explode('/',$q['author_name']); if ($q['author_name'][count($q['author_name'])-1]) { $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'"); $whichauthor .= ' AND (post_author = '.intval($q['author']).')'; } $where .= $search.$whichcat.$whichauthor; if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) { $q['order']='DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby']='date '.$q['order']; } else { // Used to filter values $allowed_keys = array('author', 'date', 'category', 'title', 'modified'); $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ',$q['orderby']); if (!in_array($orderby_array[0],$allowed_keys)) { $orderby_array[0] = 'date'; } $q['orderby'] = $orderby_array[0].' '.$q['order']; if (count($orderby_array)>1) { for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) { // Only allow certain values for safety if (in_array($orderby_array[$i],$allowed_keys)) { $q['orderby'] .= ',post_'.$orderby_array[$i].' '.$q['order']; } } } } $now = gmdate('Y-m-d H:i:59'); //only select past-dated posts, except if a logged in user is viewing a single: then, if they //can edit the post, we let them through if ($pagenow != 'post.php' && $pagenow != 'edit.php' && !($this->is_single && $user_ID)) { $where .= " AND post_date_gmt <= '$now'"; $distinct = 'DISTINCT'; } if ( $this->is_attachment ) { $where .= " AND (post_status = 'attachment')"; } elseif ($this->is_page) { $where .= " AND (post_status = 'static')"; } elseif ($this->is_single) { $where .= " AND (post_status != 'static')"; } else { $where .= " AND (post_status = 'publish'"; if (isset($user_ID) && ('' != intval($user_ID))) $where .= " OR post_author = $user_ID AND post_status != 'draft' AND post_status != 'static')"; else $where .= ')'; } if (! $this->is_attachment ) $where .= " AND post_status != 'attachment'"; // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. $where = apply_filters('posts_where', $where); $join = apply_filters('posts_join', $join); // Paging if (empty($q['nopaging']) && ! $this->is_single && ! $this->is_page) { $page = abs(intval($q['paged'])); if (empty($page)) { $page = 1; } if (($q['what_to_show'] == 'posts')) { $q['offset'] = abs(intval($q['offset'])); if ( empty($q['offset']) ) { $pgstrt = ''; $pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT '.$pgstrt.$q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $pgstrt = $q['offset'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } } elseif ($q['what_to_show'] == 'days') { $startrow = $q['posts_per_page'] * (intval($page)-1); $start_date = $wpdb->get_var("SELECT max(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $startrow,1"); $endrow = $startrow + $q['posts_per_page'] - 1; $end_date = $wpdb->get_var("SELECT min(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $endrow,1"); if ($page > 1) { $where .= " AND post_date >= '$end_date' AND post_date <= '$start_date'"; } else { $where .= " AND post_date >= '$end_date'"; } } } // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. $where = apply_filters('posts_where_paged', $where); $groupby = " $wpdb->posts.ID "; $groupby = apply_filters('posts_groupby', $groupby); $join = apply_filters('posts_join_paged', $join); $orderby = "post_" . $q['orderby']; $orderby = apply_filters('posts_orderby', $orderby); $request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1" . $where . " GROUP BY " . $groupby . " ORDER BY " . $orderby . " $limits"; $this->request = apply_filters('posts_request', $request); $this->posts = $wpdb->get_results($this->request); // Check post status to determine if post should be displayed. if ( !empty($this->posts) && $this->is_single ) { $status = get_post_status($this->posts[0]); if ( ('publish' != $status) && ('static' != $status) ) { if ( ! (isset($user_ID) && ('' != intval($user_ID))) ) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ('draft' == $status) { // User must have edit permissions on the draft to preview. if (! current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; $this->posts[0]->post_date = current_time('mysql'); } } else { if (! current_user_can('read_post', $this->posts[0]->ID)) $this->posts = array(); } } } else { if (mysql2date('U', $this->posts[0]->post_date_gmt) > mysql2date('U', $now)) { //it's future dated $this->is_preview = true; if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array ( ); } } } } update_post_caches($this->posts); $this->posts = apply_filters('the_posts', $this->posts); $this->post_count = count($this->posts); if ($this->post_count > 0) { $this->post = $this->posts[0]; } // Save any changes made to the query vars. $this->query_vars = $q; return $this->posts; }
function get_posts($args) { global $wpdb; if ( is_array($args) ) $r = &$args; else parse_str($args, $r); $defaults = array('numberposts' => 5, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'publish', 'post_parent' => 0); $r = array_merge($defaults, $r); extract($r); $numberposts = (int) $numberposts; $offset = (int) $offset; $category = (int) $category; $post_parent = (int) $post_parent; $inclusions = ''; if ( !empty($include) ) { $offset = 0; //ignore offset, category, exclude, meta_key, and meta_value, post_parent if using include $category = 0; $exclude = ''; $meta_key = ''; $meta_value = ''; $post_parent = 0; $incposts = preg_split('/[\s,]+/',$include); $numberposts = count($incposts); // only the number of posts included if ( count($incposts) ) { foreach ( $incposts as $incpost ) { if (empty($inclusions)) $inclusions = ' AND ( ID = ' . intval($incpost) . ' '; else $inclusions .= ' OR ID = ' . intval($incpost) . ' '; } } } if (!empty($inclusions)) $inclusions .= ')'; $exclusions = ''; if ( !empty($exclude) ) { $exposts = preg_split('/[\s,]+/',$exclude); if ( count($exposts) ) { foreach ( $exposts as $expost ) { if (empty($exclusions)) $exclusions = ' AND ( ID <> ' . intval($expost) . ' '; else $exclusions .= ' AND ID <> ' . intval($expost) . ' '; } } } if (!empty($exclusions)) $exclusions .= ')'; $query ="SELECT DISTINCT * FROM $wpdb->posts " ; $query .= ( empty( $category ) ? "" : ", $wpdb->post2cat " ); $query .= ( empty( $meta_key ) ? "" : ", $wpdb->postmeta " ); $query .= " WHERE (post_type = 'post' AND post_status = 'publish') $exclusions $inclusions "; $query .= ( empty( $category ) ? "" : "AND ($wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $category. ") " ); $query .= ( empty( $meta_key ) | empty($meta_value) ? "" : " AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '$meta_key' AND $wpdb->postmeta.meta_value = '$meta_value' )" ); $query .= " GROUP BY $wpdb->posts.ID ORDER BY " . $orderby . " " . $order . " LIMIT " . $offset . ',' . $numberposts; $query = "SELECT DISTINCT * FROM $wpdb->posts "; $query .= empty( $category ) ? '' : ", $wpdb->post2cat "; $query .= empty( $meta_key ) ? '' : ", $wpdb->postmeta "; $query .= " WHERE 1=1 "; $query .= empty( $post_type ) ? '' : "AND post_type = '$post_type' "; $query .= empty( $post_status ) ? '' : "AND post_status = '$post_status' "; $query .= "$exclusions $inclusions " ; $query .= empty( $category ) ? '' : "AND ($wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $category. ") "; $query .= empty( $post_parent ) ? '' : "AND $wpdb->posts.post_parent = '$post_parent' "; $query .= empty( $meta_key ) | empty($meta_value) ? '' : " AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '$meta_key' AND $wpdb->postmeta.meta_value = '$meta_value' )"; $query .= " GROUP BY $wpdb->posts.ID ORDER BY " . $orderby . ' ' . $order; if ( 0 < $numberposts ) $query .= " LIMIT " . $offset . ',' . $numberposts; $posts = $wpdb->get_results($query); update_post_caches($posts); return $posts; }
function reloadGlobals() { global $post; global $wp_query; global $id; /* * Not sure what is better out of the twop options below. this: */ wp_reset_query(); /* * or this: */ //$wp_query->the_post(); //$wp_query->rewind_posts(); /* * Acheives almost the same thing, if problems arise, investigate alternatives. */ update_post_caches($wp_query->posts); /*if($wp_query==$this->page_query){ print('== supercats if off =='); if($this->page_query->post->ID!=$id) { print_r('something is amiss '.$this->page_query->post->ID.'!='.$id); } }elseif($this->cat_query)print('== supercats is on =='); else print('supercats is broken'); */ }
function &get_posts() { global $wpdb, $pagenow, $request, $user_ID; // Shorthand. $q = $this->query_vars; // First let's clear some variables $whichcat = ''; $whichauthor = ''; $result = ''; $where = ''; $limits = ''; $distinct = ''; $join = ''; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_settings('posts_per_page'); } if (!isset($q['what_to_show'])) { $q['what_to_show'] = get_settings('what_to_show'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_settings('posts_per_rss'); $q['what_to_show'] = 'posts'; } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = (int) $q['page']; } $add_hours = intval(get_settings('gmt_offset')); $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours)); $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"; // If a month is specified in the querystring, load that month if ((int) $q['m']) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2); } } if ((int) $q['hour']) { $q['hour'] = '' . intval($q['hour']); $where .= " AND HOUR(post_date)='" . $q['hour'] . "'"; } if ((int) $q['minute']) { $q['minute'] = '' . intval($q['minute']); $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'"; } if ((int) $q['second']) { $q['second'] = '' . intval($q['second']); $where .= " AND SECOND(post_date)='" . $q['second'] . "'"; } if ((int) $q['year']) { $q['year'] = '' . intval($q['year']); $where .= " AND YEAR(post_date)='" . $q['year'] . "'"; } if ((int) $q['monthnum']) { $q['monthnum'] = '' . intval($q['monthnum']); $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'"; } if ((int) $q['day']) { $q['day'] = '' . intval($q['day']); $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'"; } if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND post_name = '" . $q['name'] . "'"; } else { if ('' != $q['pagename']) { $q['pagename'] = sanitize_title(basename(str_replace('%2F', '/', urlencode($q['pagename'])))); $q['name'] = $q['pagename']; $where .= " AND post_name = '" . $q['pagename'] . "'"; } } if ((int) $q['w']) { $q['w'] = '' . intval($q['w']); $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'"; } if (intval($q['comments_popup'])) { $q['p'] = intval($q['comments_popup']); } if ($q['p'] != '' && intval($q['p']) != 0) { $q['p'] = (int) $q['p']; $where = ' AND ID = ' . $q['p']; } if ($q['page_id'] != '' && intval($q['page_id']) != 0) { $q['page_id'] = intval($q['page_id']); $q['p'] = $q['page_id']; $where = ' AND ID = ' . $q['page_id']; } if (!empty($q['s'])) { $q['s'] = addslashes_gpc($q['s']); $search = ' AND ('; $q['s'] = preg_replace('/, +/', ' ', $q['s']); $q['s'] = str_replace(',', ' ', $q['s']); $q['s'] = str_replace('"', ' ', $q['s']); $q['s'] = trim($q['s']); if ($q['exact']) { $n = ''; } else { $n = '%'; } if (!$q['sentence']) { $s_array = explode(' ', $q['s']); $q['search_terms'] = $s_array; $search .= '((post_title LIKE \'' . $n . $s_array[0] . $n . '\') OR (post_content LIKE \'' . $n . $s_array[0] . $n . '\'))'; for ($i = 1; $i < count($s_array); $i = $i + 1) { $search .= ' AND ((post_title LIKE \'' . $n . $s_array[$i] . $n . '\') OR (post_content LIKE \'' . $n . $s_array[$i] . $n . '\'))'; } $search .= ' OR (post_title LIKE \'' . $n . $q['s'] . $n . '\') OR (post_content LIKE \'' . $n . $q['s'] . $n . '\')'; $search .= ')'; } else { $search = ' AND ((post_title LIKE \'' . $n . $q['s'] . $n . '\') OR (post_content LIKE \'' . $n . $q['s'] . $n . '\'))'; } } // Category stuff if (empty($q['cat']) || $q['cat'] == '0' || ($this->is_single || $this->is_page)) { $whichcat = ''; } else { $q['cat'] = '' . urldecode($q['cat']) . ''; $q['cat'] = addslashes_gpc($q['cat']); if (stristr($q['cat'], '-')) { // Note: if we have a negative, we ignore all the positives. It must // always mean 'everything /except/ this one'. We should be able to do // multiple negatives but we don't :-( $eq = '!='; $andor = 'AND'; $q['cat'] = explode('-', $q['cat']); $q['cat'] = intval($q['cat'][1]); } else { $eq = '='; $andor = 'OR'; } $join = " LEFT JOIN {$wpdb->post2cat} ON ({$wpdb->posts}.ID = {$wpdb->post2cat}.post_id) "; $cat_array = preg_split('/[,\\s]+/', $q['cat']); $whichcat .= ' AND (category_id ' . $eq . ' ' . intval($cat_array[0]); $whichcat .= get_category_children($cat_array[0], ' ' . $andor . ' category_id ' . $eq . ' '); for ($i = 1; $i < count($cat_array); $i = $i + 1) { $whichcat .= ' ' . $andor . ' category_id ' . $eq . ' ' . intval($cat_array[$i]); $whichcat .= get_category_children($cat_array[$i], ' ' . $andor . ' category_id ' . $eq . ' '); } $whichcat .= ')'; if ($eq == '!=') { $q['cat'] = '-' . $q['cat']; // Put back the knowledge that we are excluding a category. } } // Category stuff for nice URIs if ('' != $q['category_name']) { if (stristr($q['category_name'], '/')) { $q['category_name'] = explode('/', $q['category_name']); if ($q['category_name'][count($q['category_name']) - 1]) { $q['category_name'] = $q['category_name'][count($q['category_name']) - 1]; // no trailing slash } else { $q['category_name'] = $q['category_name'][count($q['category_name']) - 2]; // there was a trailling slash } } $q['category_name'] = sanitize_title($q['category_name']); $tables = ", {$wpdb->post2cat}, {$wpdb->categories}"; $join = " LEFT JOIN {$wpdb->post2cat} ON ({$wpdb->posts}.ID = {$wpdb->post2cat}.post_id) LEFT JOIN {$wpdb->categories} ON ({$wpdb->post2cat}.category_id = {$wpdb->categories}.cat_ID) "; $whichcat = " AND (category_nicename = '" . $q['category_name'] . "'"; $q['cat'] = $wpdb->get_var("SELECT cat_ID FROM {$wpdb->categories} WHERE category_nicename = '" . $q['category_name'] . "'"); $whichcat .= get_category_children($q['cat'], " OR category_id = "); $whichcat .= ")"; } // Author/user stuff if (empty($q['author']) || $q['author'] == '0') { $whichauthor = ''; } else { $q['author'] = '' . urldecode($q['author']) . ''; $q['author'] = addslashes_gpc($q['author']); if (stristr($q['author'], '-')) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = '' . intval($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\\s]+/', $q['author']); $whichauthor .= ' AND (post_author ' . $eq . ' ' . intval($author_array[0]); for ($i = 1; $i < count($author_array); $i = $i + 1) { $whichauthor .= ' ' . $andor . ' post_author ' . $eq . ' ' . intval($author_array[$i]); } $whichauthor .= ')'; } // Author stuff for nice URIs if ('' != $q['author_name']) { if (stristr($q['author_name'], '/')) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; #no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; #there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_nicename='" . $q['author_name'] . "'"); $whichauthor .= ' AND (post_author = ' . intval($q['author']) . ')'; } $where .= $search . $whichcat . $whichauthor; if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') { $q['order'] = 'DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby'] = 'date ' . $q['order']; } else { // Used to filter values $allowed_keys = array('author', 'date', 'category', 'title'); $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ', $q['orderby']); if (!in_array($orderby_array[0], $allowed_keys)) { $orderby_array[0] = 'date'; } $q['orderby'] = $orderby_array[0] . ' ' . $q['order']; if (count($orderby_array) > 1) { for ($i = 1; $i < count($orderby_array); $i = $i + 1) { // Only allow certain values for safety if (in_array($orderby_array[$i], $allowed_keys)) { $q['orderby'] .= ',post_' . $orderby_array[$i] . ' ' . $q['order']; } } } } $now = gmdate('Y-m-d H:i:59'); if ($pagenow != 'post.php' && $pagenow != 'edit.php') { $where .= " AND post_date_gmt <= '{$now}'"; $distinct = 'DISTINCT'; } if ($this->is_page) { $where .= ' AND (post_status = "static")'; } elseif ($this->is_single) { $where .= ' AND (post_status != "static")'; } else { $where .= ' AND (post_status = "publish"'; if (isset($user_ID) && '' != intval($user_ID)) { $where .= " OR post_author = {$user_ID} AND post_status != 'draft' AND post_status != 'static')"; } else { $where .= ')'; } } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. $where = apply_filters('posts_where', $where); $join = apply_filters('posts_join', $join); // Paging if (empty($q['nopaging']) && !$this->is_single) { $page = $q['paged']; if (empty($page)) { $page = 1; } if ($q['what_to_show'] == 'posts') { $pgstrt = ''; $pgstrt = (intval($page) - 1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } elseif ($q['what_to_show'] == 'days') { $startrow = $q['posts_per_page'] * (intval($page) - 1); $start_date = $wpdb->get_var("SELECT max(post_date) FROM {$wpdb->posts} {$join} WHERE (1=1) {$where} GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT {$startrow},1"); $endrow = $startrow + $q['posts_per_page'] - 1; $end_date = $wpdb->get_var("SELECT min(post_date) FROM {$wpdb->posts} {$join} WHERE (1=1) {$where} GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT {$endrow},1"); if ($page > 1) { $where .= " AND post_date >= '{$end_date}' AND post_date <= '{$start_date}'"; } else { $where .= " AND post_date >= '{$end_date}'"; } } } // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. $where = apply_filters('posts_where_paged', $where); $where .= " GROUP BY {$wpdb->posts}.ID"; $join = apply_filters('posts_join_paged', $join); $orderby = "post_" . $q['orderby']; $orderby = apply_filters('posts_orderby', $orderby); $request = " SELECT {$distinct} * FROM {$wpdb->posts} {$join} WHERE 1=1" . $where . " ORDER BY " . $orderby . " {$limits}"; $this->posts = $wpdb->get_results($request); // Check post status to determine if post should be displayed. if ($this->is_single) { if ('publish' != $this->posts[0]->post_status) { if (!(isset($user_ID) && '' != intval($user_ID))) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ('draft' == $this->posts[0]->post_status) { // User must have edit permissions on the draft to preview. if (!user_can_edit_post($user_ID, $this->posts[0]->ID)) { $this->posts = array(); } } elseif ('private' == $this->posts[0]->post_status) { if ($this->posts[0]->post_author != $user_ID) { $this->posts = array(); } } } } } $this->posts = apply_filters('the_posts', $this->posts); $this->post_count = count($this->posts); if ($this->post_count > 0) { $this->post = $this->posts[0]; } update_post_caches($this->posts); // Save any changes made to the query vars. $this->query_vars = $q; return $this->posts; }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @return array List of posts. */ function get_posts() { global $wpdb; $this->parse_query(); do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q = &$this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $q ); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5( serialize( $this->query_vars ) ); if ( $hash != $this->query_vars_hash ) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $fields = ''; $post_status_join = false; $page = 1; if ( isset( $q['caller_get_posts'] ) ) { _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) ); if ( !isset( $q['ignore_sticky_posts'] ) ) $q['ignore_sticky_posts'] = $q['caller_get_posts']; } if ( !isset( $q['ignore_sticky_posts'] ) ) $q['ignore_sticky_posts'] = false; if ( !isset($q['suppress_filters']) ) $q['suppress_filters'] = false; if ( !isset($q['cache_results']) ) { if ( wp_using_ext_object_cache() ) $q['cache_results'] = false; else $q['cache_results'] = true; } if ( !isset($q['update_post_term_cache']) ) $q['update_post_term_cache'] = true; if ( !isset($q['update_post_meta_cache']) ) $q['update_post_meta_cache'] = true; if ( !isset($q['post_type']) ) { if ( $this->is_search ) $q['post_type'] = 'any'; else $q['post_type'] = ''; } $post_type = $q['post_type']; if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 ) $q['posts_per_page'] = get_option('posts_per_page'); if ( isset($q['showposts']) && $q['showposts'] ) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) ) $q['posts_per_page'] = $q['posts_per_archive_page']; if ( !isset($q['nopaging']) ) { if ( $q['posts_per_page'] == -1 ) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ( $this->is_feed ) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ( $q['posts_per_page'] < -1 ) $q['posts_per_page'] = abs($q['posts_per_page']); else if ( $q['posts_per_page'] == 0 ) $q['posts_per_page'] = 1; if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 ) $q['comments_per_page'] = get_option('comments_per_page'); if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if ( isset($q['page']) ) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present. if ( isset($q['no_found_rows']) ) $q['no_found_rows'] = (bool) $q['no_found_rows']; else $q['no_found_rows'] = false; switch ( $q['fields'] ) { case 'ids': $fields = "$wpdb->posts.ID"; break; case 'id=>parent': $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent"; break; default: $fields = "$wpdb->posts.*"; } if ( '' !== $q['menu_order'] ) $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order']; // The "m" parameter is meant for months but accepts datetimes of varying specificity if ( $q['m'] ) { $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4); if ( strlen($q['m']) > 5 ) $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2); if ( strlen($q['m']) > 7 ) $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2); if ( strlen($q['m']) > 9 ) $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2); if ( strlen($q['m']) > 11 ) $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2); if ( strlen($q['m']) > 13 ) $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2); } // Handle the other individual date parameters $date_parameters = array(); if ( '' !== $q['hour'] ) $date_parameters['hour'] = $q['hour']; if ( '' !== $q['minute'] ) $date_parameters['minute'] = $q['minute']; if ( '' !== $q['second'] ) $date_parameters['second'] = $q['second']; if ( $q['year'] ) $date_parameters['year'] = $q['year']; if ( $q['monthnum'] ) $date_parameters['monthnum'] = $q['monthnum']; if ( $q['w'] ) $date_parameters['week'] = $q['w']; if ( $q['day'] ) $date_parameters['day'] = $q['day']; if ( $date_parameters ) { $date_query = new WP_Date_Query( array( $date_parameters ) ); $where .= $date_query->get_sql(); } unset( $date_parameters, $date_query ); // Handle complex date queries if ( ! empty( $q['date_query'] ) ) { $this->date_query = new WP_Date_Query( $q['date_query'] ); $where .= $this->date_query->get_sql(); } // If we've got a post_type AND it's not "any" post_type. if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) { foreach ( (array)$q['post_type'] as $_post_type ) { $ptype_obj = get_post_type_object($_post_type); if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) ) continue; if ( ! $ptype_obj->hierarchical || strpos($q[ $ptype_obj->query_var ], '/') === false ) { // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name' $q['name'] = $q[ $ptype_obj->query_var ]; } else { // Hierarchical post_types will operate through the $q['pagename'] = $q[ $ptype_obj->query_var ]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ( '' != $q['name'] ) { $q['name'] = sanitize_title_for_query( $q['name'] ); $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'"; } elseif ( '' != $q['pagename'] ) { if ( isset($this->queried_object_id) ) { $reqpage = $this->queried_object_id; } else { if ( 'page' != $q['post_type'] ) { foreach ( (array)$q['post_type'] as $_post_type ) { $ptype_obj = get_post_type_object($_post_type); if ( !$ptype_obj || !$ptype_obj->hierarchical ) continue; $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ( $reqpage ) break; } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if ( !empty($reqpage) ) $reqpage = $reqpage->ID; else $reqpage = 0; } $page_for_posts = get_option('page_for_posts'); if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) { $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) ); $q['name'] = $q['pagename']; $where .= " AND ($wpdb->posts.ID = '$reqpage')"; $reqpage_obj = get_post( $reqpage ); if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ( '' != $q['attachment'] ) { $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) ); $q['name'] = $q['attachment']; $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'"; } if ( intval($q['comments_popup']) ) $q['p'] = absint($q['comments_popup']); // If an attachment is requested by number, let it supersede any post number. if ( $q['attachment_id'] ) $q['p'] = absint($q['attachment_id']); // If a post number is specified, load that post if ( $q['p'] ) { $where .= " AND {$wpdb->posts}.ID = " . $q['p']; } elseif ( $q['post__in'] ) { $post__in = implode(',', array_map( 'absint', $q['post__in'] )); $where .= " AND {$wpdb->posts}.ID IN ($post__in)"; } elseif ( $q['post__not_in'] ) { $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] )); $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)"; } if ( is_numeric( $q['post_parent'] ) ) { $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] ); } elseif ( $q['post_parent__in'] ) { $post_parent__in = implode( ',', array_map( 'absint', $q['post_parent__in'] ) ); $where .= " AND {$wpdb->posts}.post_parent IN ($post_parent__in)"; } elseif ( $q['post_parent__not_in'] ) { $post_parent__not_in = implode( ',', array_map( 'absint', $q['post_parent__not_in'] ) ); $where .= " AND {$wpdb->posts}.post_parent NOT IN ($post_parent__not_in)"; } if ( $q['page_id'] ) { if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) { $q['p'] = $q['page_id']; $where = " AND {$wpdb->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match. if ( ! empty( $q['s'] ) ) $search = $this->parse_search( $q ); /** * Filter the search SQL that is used in the WHERE clause of WP_Query. * * @since 3.0.0 * * @param string $search Search SQL for WHERE clause. * @param WP_Query $this The current WP_Query object. */ $search = apply_filters_ref_array( 'posts_search', array( $search, &$this ) ); // Taxonomies if ( !$this->is_singular ) { $this->parse_tax_query( $q ); $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' ); $join .= $clauses['join']; $where .= $clauses['where']; } if ( $this->is_tax ) { if ( empty($post_type) ) { // Do a fully inclusive search for currently registered post types of queried taxonomies $post_type = array(); $taxonomies = wp_list_pluck( $this->tax_query->queries, 'taxonomy' ); foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) { $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt ); if ( array_intersect( $taxonomies, $object_taxonomies ) ) $post_type[] = $pt; } if ( ! $post_type ) $post_type = 'any'; elseif ( count( $post_type ) == 1 ) $post_type = $post_type[0]; $post_status_join = true; } elseif ( in_array('attachment', (array) $post_type) ) { $post_status_join = true; } } // Back-compat if ( !empty($this->tax_query->queries) ) { $tax_query_in_and = wp_list_filter( $this->tax_query->queries, array( 'operator' => 'NOT IN' ), 'NOT' ); if ( !empty( $tax_query_in_and ) ) { if ( !isset( $q['taxonomy'] ) ) { foreach ( $tax_query_in_and as $a_tax_query ) { if ( !in_array( $a_tax_query['taxonomy'], array( 'category', 'post_tag' ) ) ) { $q['taxonomy'] = $a_tax_query['taxonomy']; if ( 'slug' == $a_tax_query['field'] ) $q['term'] = $a_tax_query['terms'][0]; else $q['term_id'] = $a_tax_query['terms'][0]; break; } } } $cat_query = wp_list_filter( $tax_query_in_and, array( 'taxonomy' => 'category' ) ); if ( ! empty( $cat_query ) ) { $cat_query = reset( $cat_query ); if ( ! empty( $cat_query['terms'][0] ) ) { $the_cat = get_term_by( $cat_query['field'], $cat_query['terms'][0], 'category' ); if ( $the_cat ) { $this->set( 'cat', $the_cat->term_id ); $this->set( 'category_name', $the_cat->slug ); } unset( $the_cat ); } } unset( $cat_query ); $tag_query = wp_list_filter( $tax_query_in_and, array( 'taxonomy' => 'post_tag' ) ); if ( ! empty( $tag_query ) ) { $tag_query = reset( $tag_query ); if ( ! empty( $tag_query['terms'][0] ) ) { $the_tag = get_term_by( $tag_query['field'], $tag_query['terms'][0], 'post_tag' ); if ( $the_tag ) $this->set( 'tag_id', $the_tag->term_id ); unset( $the_tag ); } } unset( $tag_query ); } } if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) { $groupby = "{$wpdb->posts}.ID"; } // Author/user stuff if ( ! empty( $q['author'] ) && $q['author'] != '0' ) { $q['author'] = addslashes_gpc( '' . urldecode( $q['author'] ) ); $authors = array_unique( array_map( 'intval', preg_split( '/[,\s]+/', $q['author'] ) ) ); foreach ( $authors as $author ) { $key = $author > 0 ? 'author__in' : 'author__not_in'; $q[$key][] = abs( $author ); } $q['author'] = implode( ',', $authors ); } if ( ! empty( $q['author__not_in'] ) ) { $author__not_in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__not_in'] ) ) ); $where .= " AND {$wpdb->posts}.post_author NOT IN ($author__not_in) "; } elseif ( ! empty( $q['author__in'] ) ) { $author__in = implode( ',', array_map( 'absint', array_unique( (array) $q['author__in'] ) ) ); $where .= " AND {$wpdb->posts}.post_author IN ($author__in) "; } // Author stuff for nice URLs if ( '' != $q['author_name'] ) { if ( strpos($q['author_name'], '/') !== false ) { $q['author_name'] = explode('/', $q['author_name']); if ( $q['author_name'][ count($q['author_name'])-1 ] ) { $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query( $q['author_name'] ); $q['author'] = get_user_by('slug', $q['author_name']); if ( $q['author'] ) $q['author'] = $q['author']->ID; $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] ) $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts ); $where .= $search . $whichauthor . $whichmimetype; if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) ) $q['order'] = 'DESC'; // Order by if ( empty($q['orderby']) ) { $orderby = "$wpdb->posts.post_date " . $q['order']; } elseif ( 'none' == $q['orderby'] ) { $orderby = ''; } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) { $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )"; } elseif ( $q['orderby'] == 'post_parent__in' && ! empty( $post_parent__in ) ) { $orderby = "FIELD( {$wpdb->posts}.post_parent, $post_parent__in )"; } else { // Used to filter values $allowed_keys = array('name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count'); if ( !empty($q['meta_key']) ) { $allowed_keys[] = $q['meta_key']; $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; } $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = array(); foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) { // Only allow certain values for safety if ( ! in_array($orderby, $allowed_keys) ) continue; switch ( $orderby ) { case 'menu_order': $orderby = "$wpdb->posts.menu_order"; break; case 'ID': $orderby = "$wpdb->posts.ID"; break; case 'rand': $orderby = 'RAND()'; break; case $q['meta_key']: case 'meta_value': if ( isset( $q['meta_type'] ) ) { $meta_type = $this->meta_query->get_cast_for_type( $q['meta_type'] ); $orderby = "CAST($wpdb->postmeta.meta_value AS {$meta_type})"; } else { $orderby = "$wpdb->postmeta.meta_value"; } break; case 'meta_value_num': $orderby = "$wpdb->postmeta.meta_value+0"; break; case 'comment_count': $orderby = "$wpdb->posts.comment_count"; break; default: $orderby = "$wpdb->posts.post_" . $orderby; } $orderby_array[] = $orderby; } $orderby = implode( ',', $orderby_array ); if ( empty( $orderby ) ) $orderby = "$wpdb->posts.post_date ".$q['order']; else $orderby .= " {$q['order']}"; } // Order search results by relevance only when another "orderby" is not specified in the query. if ( ! empty( $q['s'] ) ) { $search_orderby = ''; if ( ! empty( $q['search_orderby_title'] ) && ( empty( $q['orderby'] ) && ! $this->is_feed ) || ( isset( $q['orderby'] ) && 'relevance' === $q['orderby'] ) ) $search_orderby = $this->parse_search_order( $q ); /** * Filter the ORDER BY used when ordering search results. * * @since 3.7.0 * * @param string $search_orderby The ORDER BY clause. * @param WP_Query $this The current WP_Query instance. */ $search_orderby = apply_filters( 'posts_search_orderby', $search_orderby, $this ); if ( $search_orderby ) $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby; } if ( is_array( $post_type ) && count( $post_type ) > 1 ) { $post_type_cap = 'multiple_post_type'; } else { if ( is_array( $post_type ) ) $post_type = reset( $post_type ); $post_type_object = get_post_type_object( $post_type ); if ( empty( $post_type_object ) ) $post_type_cap = $post_type; } if ( 'any' == $post_type ) { $in_search_post_types = get_post_types( array('exclude_from_search' => false) ); if ( empty( $in_search_post_types ) ) $where .= ' AND 1=0 '; else $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')"; } elseif ( !empty( $post_type ) && is_array( $post_type ) ) { $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')"; } elseif ( ! empty( $post_type ) ) { $where .= " AND $wpdb->posts.post_type = '$post_type'"; $post_type_object = get_post_type_object ( $post_type ); } elseif ( $this->is_attachment ) { $where .= " AND $wpdb->posts.post_type = 'attachment'"; $post_type_object = get_post_type_object ( 'attachment' ); } elseif ( $this->is_page ) { $where .= " AND $wpdb->posts.post_type = 'page'"; $post_type_object = get_post_type_object ( 'page' ); } else { $where .= " AND $wpdb->posts.post_type = 'post'"; $post_type_object = get_post_type_object ( 'post' ); } $edit_cap = 'edit_post'; $read_cap = 'read_post'; if ( ! empty( $post_type_object ) ) { $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } $user_id = get_current_user_id(); if ( ! empty( $q['post_status'] ) ) { $statuswheres = array(); $q_status = $q['post_status']; if ( ! is_array( $q_status ) ) $q_status = explode(',', $q_status); $r_status = array(); $p_status = array(); $e_status = array(); if ( in_array('any', $q_status) ) { foreach ( get_post_stati( array('exclude_from_search' => true) ) as $status ) $e_status[] = "$wpdb->posts.post_status <> '$status'"; } else { foreach ( get_post_stati() as $status ) { if ( in_array( $status, $q_status ) ) { if ( 'private' == $status ) $p_status[] = "$wpdb->posts.post_status = '$status'"; else $r_status[] = "$wpdb->posts.post_status = '$status'"; } } } if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if ( !empty($e_status) ) { $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")"; } if ( !empty($r_status) ) { if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) ) $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $r_status ) . "))"; else $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")"; } if ( !empty($p_status) ) { if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) ) $statuswheres[] = "($wpdb->posts.post_author = $user_id " . "AND (" . join( ' OR ', $p_status ) . "))"; else $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")"; } if ( $post_status_join ) { $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) "; foreach ( $statuswheres as $index => $statuswhere ) $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; } foreach ( $statuswheres as $statuswhere ) $where .= " AND $statuswhere"; } elseif ( !$this->is_singular ) { $where .= " AND ($wpdb->posts.post_status = 'publish'"; // Add public states. $public_states = get_post_stati( array('public' => true) ); foreach ( (array) $public_states as $state ) { if ( 'publish' == $state ) // Publish is hard-coded above. continue; $where .= " OR $wpdb->posts.post_status = '$state'"; } if ( $this->is_admin ) { // Add protected states that should show in the admin all list. $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) ); foreach ( (array) $admin_all_states as $state ) $where .= " OR $wpdb->posts.post_status = '$state'"; } if ( is_user_logged_in() ) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati( array('private' => true) ); foreach ( (array) $private_states as $state ) $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'"; } $where .= ')'; } if ( !empty( $this->meta_query->queries ) ) { $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this ); $join .= $clauses['join']; $where .= $clauses['where']; } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. if ( !$q['suppress_filters'] ) { $where = apply_filters_ref_array('posts_where', array( $where, &$this ) ); $join = apply_filters_ref_array('posts_join', array( $join, &$this ) ); } // Paging if ( empty($q['nopaging']) && !$this->is_singular ) { $page = absint($q['paged']); if ( !$page ) $page = 1; if ( empty($q['offset']) ) { $pgstrt = ($page - 1) * $q['posts_per_page'] . ', '; } else { // we're ignoring $page and using 'offset' $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; } $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } // Comments feeds if ( $this->is_comment_feed && ( $this->is_archive || $this->is_search || !$this->is_singular ) ) { if ( $this->is_archive || $this->is_search ) { $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join "; $cwhere = "WHERE comment_approved = '1' $where"; $cgroupby = "$wpdb->comments.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if ( !$q['suppress_filters'] ) { $cjoin = apply_filters_ref_array('comment_feed_join', array( $cjoin, &$this ) ); $cwhere = apply_filters_ref_array('comment_feed_where', array( $cwhere, &$this ) ); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array( $cgroupby, &$this ) ); $corderby = apply_filters_ref_array('comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) ); $climits = apply_filters_ref_array('comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) ); } $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : ''; $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : ''; $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits"); $this->comment_count = count($this->comments); $post_ids = array(); foreach ( $this->comments as $comment ) $post_ids[] = (int) $comment->comment_post_ID; $post_ids = join(',', $post_ids); $join = ''; if ( $post_ids ) $where = "AND $wpdb->posts.ID IN ($post_ids) "; else $where = "AND 0"; } $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' ); // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. if ( !$q['suppress_filters'] ) { $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) ); $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) ); $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) ); $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) ); $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) ); $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) ); $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) ); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) ); foreach ( $pieces as $piece ) $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : ''; } // Announce current selection parameters. For use by caching plugins. do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join ); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if ( !$q['suppress_filters'] ) { $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) ); $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) ); $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) ); $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) ); $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) ); $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) ); $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) ); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) ); foreach ( $pieces as $piece ) $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : ''; } if ( ! empty($groupby) ) $groupby = 'GROUP BY ' . $groupby; if ( !empty( $orderby ) ) $orderby = 'ORDER BY ' . $orderby; $found_rows = ''; if ( !$q['no_found_rows'] && !empty($limits) ) $found_rows = 'SQL_CALC_FOUND_ROWS'; $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits"; if ( !$q['suppress_filters'] ) { $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) ); } if ( 'ids' == $q['fields'] ) { $this->posts = $wpdb->get_col( $this->request ); $this->post_count = count( $this->posts ); $this->set_found_posts( $q, $limits ); return $this->posts; } if ( 'id=>parent' == $q['fields'] ) { $this->posts = $wpdb->get_results( $this->request ); $this->post_count = count( $this->posts ); $this->set_found_posts( $q, $limits ); $r = array(); foreach ( $this->posts as $post ) $r[ $post->ID ] = $post->post_parent; return $r; } $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 ); $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this ); if ( $split_the_query ) { // First get the IDs and then fill in the objects $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits"; $this->request = apply_filters( 'posts_request_ids', $this->request, $this ); $ids = $wpdb->get_col( $this->request ); if ( $ids ) { $this->posts = $ids; $this->set_found_posts( $q, $limits ); _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] ); } else { $this->posts = array(); } } else { $this->posts = $wpdb->get_results( $this->request ); $this->set_found_posts( $q, $limits ); } // Convert to WP_Post objects if ( $this->posts ) $this->posts = array_map( 'get_post', $this->posts ); // Raw results filter. Prior to status checks. if ( !$q['suppress_filters'] ) $this->posts = apply_filters_ref_array('posts_results', array( $this->posts, &$this ) ); if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) { $cjoin = apply_filters_ref_array('comment_feed_join', array( '', &$this ) ); $cwhere = apply_filters_ref_array('comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) ); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array( '', &$this ) ); $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : ''; $corderby = apply_filters_ref_array('comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) ); $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : ''; $climits = apply_filters_ref_array('comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) ); $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits"; $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) { $status = get_post_status($this->posts[0]); $post_status_obj = get_post_status_object($status); //$type = get_post_type($this->posts[0]); if ( !$post_status_obj->public ) { if ( ! is_user_logged_in() ) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ( $post_status_obj->protected ) { // User must have edit permissions on the draft to preview. if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) { $this->posts = array(); } else { $this->is_preview = true; if ( 'future' != $status ) $this->posts[0]->post_date = current_time('mysql'); } } elseif ( $post_status_obj->private ) { if ( ! current_user_can($read_cap, $this->posts[0]->ID) ) $this->posts = array(); } else { $this->posts = array(); } } } if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) ); } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ( $i = 0; $i < $num_posts; $i++ ) { if ( in_array($this->posts[$i]->ID, $sticky_posts) ) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset( $sticky_posts[$offset] ); } } // If any posts have been excluded specifically, Ignore those that are sticky. if ( !empty($sticky_posts) && !empty($q['post__not_in']) ) $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); // Fetch sticky posts that weren't in the query results if ( !empty($sticky_posts) ) { $stickies = get_posts( array( 'post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true ) ); foreach ( $stickies as $sticky_post ) { array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) ); $sticky_offset++; } } } if ( !$q['suppress_filters'] ) $this->posts = apply_filters_ref_array('the_posts', array( $this->posts, &$this ) ); // Ensure that any posts added/modified via one of the filters above are // of the type WP_Post and are filtered. if ( $this->posts ) { $this->post_count = count( $this->posts ); $this->posts = array_map( 'get_post', $this->posts ); if ( $q['cache_results'] ) update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); $this->post = reset( $this->posts ); } else { $this->post_count = 0; $this->posts = array(); } return $this->posts; }
function dito_doDiarioSidebar() { global $post; echo '<div class="boxesBox"><h2 class="blue">Ultime dal Diario</h2>'; $my_query = new WP_Query("cat=138&showposts=2"); while ($my_query->have_posts()) { $my_query->the_post(); update_post_caches($posts); $title = $post->post_title; $link = get_permalink($post->ID); $shortContentText = $post->post_content; $shortContentText = strip_tags($shortContentText); $shortContentText = substr($shortContentText, 0, 800); $lastSpaceOnEarth = strpos($shortContentText, '.', 10); $shortContentText = substr($shortContentText, 0, $lastSpaceOnEarth + 1); $shortContentText = str_replace(".", ".<br/>", $shortContentText); echo '<div class="boxesSecondLine"><a href="' . $link . '">' . $title . '</a><br/>' . $shortContentText . '</div>'; } rewind_posts(); if (!is_category()) { echo '<div class="boxesSecondLine segnalaRight"> <p class="segnala2"><a href="' . get_bloginfo('url') . '/category/dito-in-missione" class="segnala">Tutto il Diario</a></p></div></div>'; } }
function ultimate_get_posts() { global $wpdb, $table_prefix, $posts, $id, $wp_query, $request, $utw, $typelimitsql; $tabletags = $table_prefix . 'tags'; $tablepost2tag = $table_prefix . "post2tag"; $or_query = false; $tags = get_query_var("tag"); $tagset = explode(" ", $tags); if (count($tagset) == 1) { $tagset = explode("|", $tags); $or_query = true; } $tags = array(); foreach ($tagset as $tag) { $tags[] = "'" . stripslashes($utw->GetCanonicalTag($tag)) . "'"; } $tags = array_unique($tags); $tagcount = count($tags); if (strpos($request, "HAVING COUNT(ID)") == false && !$or_query) { $request = preg_replace("/ORDER BY/", "HAVING COUNT(ID) = {$tagcount} ORDER BY", $request); } $request = preg_replace("/post_type = 'post'/", "{$typelimitsql}", $request); $posts = $wpdb->get_results($request); // As requested by Splee and copperleaf $wp_query->is_home = false; // Thanks Mark! http://txfx.net/ $posts = apply_filters('the_posts', $posts); $wp_query->posts = $posts; $wp_query->post_count = count($posts); update_post_caches($posts); if ($wp_query->post_count > 0) { $wp_query->post = $wp_query->posts[0]; // Thanks Bill! http://www.copperleaf.org $wp_query->is_404 = false; } }
function &get_posts() { global $wpdb, $pagenow, $user_ID; do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; $q = $this->fill_query_vars($q); // First let's clear some variables $distinct = ''; $whichcat = ''; $whichauthor = ''; $whichpage = ''; $result = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; if (!isset($q['post_type'])) { $q['post_type'] = 'post'; } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = (int) $q['page']; $q['page'] = abs($q['page']); } $add_hours = intval(get_option('gmt_offset')); $add_minutes = intval(60 * (get_option('gmt_offset') - $add_hours)); $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"; // If a month is specified in the querystring, load that month if ($q['m']) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2); } } if ('' !== $q['hour']) { $where .= " AND HOUR(post_date)='" . $q['hour'] . "'"; } if ('' !== $q['minute']) { $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'"; } if ('' !== $q['second']) { $where .= " AND SECOND(post_date)='" . $q['second'] . "'"; } if ($q['year']) { $where .= " AND YEAR(post_date)='" . $q['year'] . "'"; } if ($q['monthnum']) { $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'"; } if ($q['day']) { $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'"; } if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND post_name = '" . $q['name'] . "'"; } else { if ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { $reqpage = get_page_by_path($q['pagename']); if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } if ('page' != get_option('show_on_front') || $reqpage != get_option('page_for_posts')) { $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename']))); $page_paths = '/' . trim($q['pagename'], '/'); $q['pagename'] = sanitize_title(basename($page_paths)); $q['name'] = $q['pagename']; $where .= " AND (ID = '{$reqpage}')"; } } elseif ('' != $q['attachment']) { $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment']))); $attach_paths = '/' . trim($q['attachment'], '/'); $q['attachment'] = sanitize_title(basename($attach_paths)); $q['name'] = $q['attachment']; $where .= " AND post_name = '" . $q['attachment'] . "'"; } } if ($q['w']) { $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'"; } if (intval($q['comments_popup'])) { $q['p'] = intval($q['comments_popup']); } // If an attachment is requested by number, let it supercede any post number. if ($q['attachment_id']) { $q['p'] = $q['attachment_id']; } // If a post number is specified, load that post if ($q['p']) { $where = ' AND ID = ' . $q['p']; } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $where = ' AND ID = ' . $q['page_id']; } } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { // added slashes screw with quote grouping when done early, so done later $q['s'] = stripslashes($q['s']); if ($q['sentence']) { $q['search_terms'] = array($q['s']); } else { preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q[s], $matches); $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]); } $n = $q['exact'] ? '' : '%'; $searchand = ''; foreach ((array) $q['search_terms'] as $term) { $term = addslashes_gpc($term); $search .= "{$searchand}((post_title LIKE '{$n}{$term}{$n}') OR (post_content LIKE '{$n}{$term}{$n}'))"; $searchand = ' AND '; } $term = addslashes_gpc($q['s']); if (!$q['sentence'] && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) { $search .= " OR (post_title LIKE '{$n}{$term}{$n}') OR (post_content LIKE '{$n}{$term}{$n}')"; } if (!empty($search)) { $search = " AND ({$search}) "; } } // Category stuff if (empty($q['cat']) || $q['cat'] == '0' || $this->is_singular) { $whichcat = ''; } else { $q['cat'] = '' . urldecode($q['cat']) . ''; $q['cat'] = addslashes_gpc($q['cat']); $cat_array = preg_split('/[,\\s]+/', $q['cat']); foreach ($cat_array as $cat) { $cat = intval($cat); $in = $cat > 0; $cat = abs($cat); if ($in) { $q['category__in'][] = $cat; $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category')); } else { $q['category__not_in'][] = $cat; $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category')); } } } if (!empty($q['category__in']) || !empty($q['category__not_in']) || !empty($q['category__and'])) { $groupby = "{$wpdb->posts}.ID"; } if (!empty($q['category__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'category' "; $include_cats = "'" . implode("', '", $q['category__in']) . "'"; $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_cats}) "; } if (!empty($q['category__not_in'])) { $ids = get_objects_in_term($q['category__not_in'], 'category'); if (is_wp_error($ids)) { return $ids; } if (is_array($ids) && count($ids > 0)) { $out_posts = "'" . implode("', '", $ids) . "'"; $whichcat .= " AND {$wpdb->posts}.ID NOT IN ({$out_posts})"; } } // Category stuff for nice URLs if ('' != $q['category_name']) { $reqcat = get_category_by_path($q['category_name']); $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name']))); $cat_paths = '/' . trim($q['category_name'], '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = '/' . trim(urldecode($q['category_name']), '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = explode('/', $cat_paths); $cat_path = ''; foreach ((array) $cat_paths as $pathdir) { $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir); } //if we don't match the entire hierarchy fallback on just matching the nicename if (empty($reqcat)) { $reqcat = get_category_by_path($q['category_name'], false); } if (!empty($reqcat)) { $reqcat = $reqcat->term_id; } else { $reqcat = 0; } $q['cat'] = $reqcat; $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) "; $whichcat = " AND {$wpdb->term_taxonomy}.taxonomy = 'category' "; $in_cats = array($q['cat']); $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category')); $in_cats = "'" . implode("', '", $in_cats) . "'"; $whichcat .= "AND {$wpdb->term_taxonomy}.term_id IN ({$in_cats})"; $groupby = "{$wpdb->posts}.ID"; } // Tags if ('' != $q['tag']) { if (strpos($q['tag'], ',') !== false) { $tags = preg_split('/[,\\s]+/', $q['tag']); foreach ((array) $tags as $tag) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $tag; } } else { if (preg_match('/[+\\s]+/', $q['tag'])) { $tags = preg_split('/[+\\s]+/', $q['tag']); foreach ((array) $tags as $tag) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__and'][] = $tag; } } else { $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db'); $reqtag = is_term($q['tag'], 'post_tag'); if (!empty($reqtag)) { $reqtag = $reqtag['term_id']; } else { $reqtag = 0; } $q['tag_id'] = $reqtag; $q['tag__in'][] = $reqtag; } } } if (!empty($q['tag__in']) || !empty($q['tag__not_in']) || !empty($q['tag__and']) || !empty($q['tag_slug__in']) || !empty($q['tag_slug__and'])) { $groupby = "{$wpdb->posts}.ID"; } if (!empty($q['tag__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' "; $include_tags = "'" . implode("', '", $q['tag__in']) . "'"; $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_tags}) "; $reqtag = is_term($q['tag__in'][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } if (!empty($q['tag_slug__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' "; $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'"; $whichcat .= " AND {$wpdb->terms}.slug IN ({$include_tags}) "; $reqtag = is_term($q['tag_slug__in'][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } if (!empty($q['tag__not_in'])) { $ids = get_objects_in_term($q['tag__not_in'], 'post_tag'); if (is_array($ids) && count($ids > 0)) { $out_posts = "'" . implode("', '", $ids) . "'"; $whichcat .= " AND {$wpdb->posts}.ID NOT IN ({$out_posts})"; } } // Tag and slug intersections. $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag'); foreach ($intersections as $item => $taxonomy) { if (empty($q[$item])) { continue; } if ($item != 'category__and') { $reqtag = is_term($q[$item][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } $taxonomy_field = $item == 'tag_slug__and' ? 'slug' : 'term_id'; $q[$item] = array_unique($q[$item]); $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)"; $tsql .= " WHERE tt.taxonomy = '{$taxonomy}' AND t.{$taxonomy_field} IN ('" . implode("', '", $q[$item]) . "')"; $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]); $post_ids = $wpdb->get_col($tsql); if (count($post_ids)) { $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") "; } else { $whichcat = " AND 0 = 1"; break; } } // Author/user stuff if (empty($q['author']) || $q['author'] == '0') { $whichauthor = ''; } else { $q['author'] = '' . urldecode($q['author']) . ''; $q['author'] = addslashes_gpc($q['author']); if (strpos($q['author'], '-') !== false) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = '' . intval($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\\s]+/', $q['author']); $whichauthor .= ' AND (post_author ' . $eq . ' ' . intval($author_array[0]); for ($i = 1; $i < count($author_array); $i = $i + 1) { $whichauthor .= ' ' . $andor . ' post_author ' . $eq . ' ' . intval($author_array[$i]); } $whichauthor .= ')'; } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; #no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; #there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_nicename='" . $q['author_name'] . "'"); $whichauthor .= ' AND (post_author = ' . intval($q['author']) . ')'; } $where .= $search . $whichcat . $whichauthor; if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') { $q['order'] = 'DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby'] = 'post_date ' . $q['order']; } else { // Used to filter values $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order'); $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ', $q['orderby']); if (empty($orderby_array)) { $orderby_array[] = $q['orderby']; } $q['orderby'] = ''; for ($i = 0; $i < count($orderby_array); $i++) { // Only allow certain values for safety $orderby = $orderby_array[$i]; if ('menu_order' != $orderby) { $orderby = 'post_' . $orderby; } if (in_array($orderby_array[$i], $allowed_keys)) { $q['orderby'] .= ($i == 0 ? '' : ',') . "{$orderby} {$q['order']}"; } } if (empty($q['orderby'])) { $q['orderby'] = 'post_date ' . $q['order']; } } if ($this->is_attachment) { $where .= " AND post_type = 'attachment'"; } elseif ($this->is_page) { $where .= " AND post_type = 'page'"; } elseif ($this->is_single) { $where .= " AND post_type = 'post'"; } else { $where .= " AND post_type = '{$post_type}'"; } if (isset($q['post_status']) && '' != $q['post_status']) { $q_status = explode(',', $q['post_status']); $r_status = array(); if (in_array('draft', $q_status)) { $r_status[] = "post_status = 'draft'"; } if (in_array('pending', $q_status)) { $r_status[] = "post_status = 'pending'"; } if (in_array('future', $q_status)) { $r_status[] = "post_status = 'future'"; } if (in_array('inherit', $q_status)) { $r_status[] = "post_status = 'inherit'"; } if (in_array('private', $q_status)) { $r_status[] = "post_status = 'private'"; } if (in_array('publish', $q_status)) { $r_status[] = "post_status = 'publish'"; } if (!empty($r_status)) { $where .= " AND (" . join(' OR ', $r_status) . ")"; } } elseif (!$this->is_singular) { $where .= " AND (post_status = 'publish'"; if (is_admin()) { $where .= " OR post_status = 'future' OR post_status = 'draft' OR post_status = 'pending'"; } if (is_user_logged_in()) { $where .= current_user_can("read_private_{$post_type}s") ? " OR post_status = 'private'" : " OR post_author = {$user_ID} AND post_status = 'private'"; } $where .= ')'; } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. $where = apply_filters('posts_where', $where); $join = apply_filters('posts_join', $join); // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = abs(intval($q['paged'])); if (empty($page)) { $page = 1; } if (empty($q['offset'])) { $pgstrt = ''; $pgstrt = (intval($page) - 1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $q['offset'] = abs(intval($q['offset'])); $pgstrt = $q['offset'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } } // Comments feeds if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) { if ($this->is_archive || $this->is_search) { $cjoin = "LEFT JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "GROUP BY {$wpdb->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "LEFT JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } $cjoin = apply_filters('comment_feed_join', $cjoin); $cwhere = apply_filters('comment_feed_where', $cwhere); $cgroupby = apply_filters('comment_feed_groupby', $cgroupby); $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss')); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. // Announce current selection parameters. For use by caching plugins. do_action('posts_selection', $where . $groupby . $q['orderby'] . $limits . $join); $where = apply_filters('posts_where_paged', $where); $groupby = apply_filters('posts_groupby', $groupby); if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } $join = apply_filters('posts_join_paged', $join); $orderby = apply_filters('posts_orderby', $q['orderby']); if (!empty($orderby)) { $orderby = 'ORDER BY ' . $orderby; } $distinct = apply_filters('posts_distinct', $distinct); $fields = apply_filters('posts_fields', "{$wpdb->posts}.*"); $limits = apply_filters('post_limits', $limits); $found_rows = ''; if (!empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; $this->request = apply_filters('posts_request', $request); $this->posts = $wpdb->get_results($this->request); // Raw results filter. Prior to status checks. $this->posts = apply_filters('posts_results', $this->posts); if ($this->is_comment_feed && $this->is_singular) { $cjoin = apply_filters('comment_feed_join', ''); $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = {$this->posts[0]->ID} AND comment_approved = '1'"); $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss'); $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } if (!empty($limits)) { $found_posts_query = apply_filters('found_posts_query', 'SELECT FOUND_ROWS()'); $this->found_posts = $wpdb->get_var($found_posts_query); $this->found_posts = apply_filters('found_posts', $this->found_posts); $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); //$type = get_post_type($this->posts[0]); if ('publish' != $status) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if (in_array($status, array('draft', 'pending'))) { // User must have edit permissions on the draft to preview. if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; $this->posts[0]->post_date = current_time('mysql'); } } else { if ('future' == $status) { $this->is_preview = true; if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } } else { if (!current_user_can('read_post', $this->posts[0]->ID)) { $this->posts = array(); } } } } } } $this->posts = apply_filters('the_posts', $this->posts); update_post_caches($this->posts); $this->post_count = count($this->posts); if ($this->post_count > 0) { $this->post = $this->posts[0]; } return $this->posts; }
function ms_motogp_table() { $args = array('posts_per_page' => '1', 'post_status' => 'publish', 'post_type' => 'riderstandings', 'name' => 'motogp'); $query = new WP_Query($args); if ($query->have_posts()) { // Start looping over the query results. while ($query->have_posts()) { $query->the_post(); if (have_rows('standings_table')) { ?> <h2>Championship Standings</h2> <table class="homestandings"> <?php $i = 1; while (have_rows('standings_table')) { the_row(); if ($i <= 5) { ?> <tr> <td><?php echo $i; ?> </td> <td><?php the_sub_field('rider'); ?> </td> <td><?php the_sub_field('points'); ?> </td> </tr> <?php } $i++; } ?> </table> <?php } } } update_post_caches($posts); wp_reset_query(); }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @return array List of posts. */ function &get_posts() { global $wpdb, $user_ID; do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; $q = $this->fill_query_vars($q); // First let's clear some variables $distinct = ''; $whichcat = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $fields = "{$wpdb->posts}.*"; $post_status_join = false; $page = 1; if (!isset($q['caller_get_posts'])) { $q['caller_get_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = 'post'; } } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If a month is specified in the querystring, load that month if ($q['m']) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2); } } if ('' !== $q['hour']) { $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'"; } if ('' !== $q['minute']) { $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'"; } if ('' !== $q['second']) { $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'"; } if ($q['year']) { $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'"; } if ($q['monthnum']) { $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'"; } if ($q['day']) { $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'"; } if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'"; } else { if ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { $reqpage = get_page_by_path($q['pagename']); if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename']))); $page_paths = '/' . trim($q['pagename'], '/'); $q['pagename'] = sanitize_title(basename($page_paths)); $q['name'] = $q['pagename']; $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')"; $reqpage_obj = get_page($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment']))); $attach_paths = '/' . trim($q['attachment'], '/'); $q['attachment'] = sanitize_title(basename($attach_paths)); $q['name'] = $q['attachment']; $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'"; } } if ($q['w']) { $where .= " AND WEEK({$wpdb->posts}.post_date, 1)='" . $q['w'] . "'"; } if (intval($q['comments_popup'])) { $q['p'] = absint($q['comments_popup']); } // If an attachment is requested by number, let it supercede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $where .= " AND {$wpdb->posts}.ID = " . $q['p']; } elseif ($q['post__in']) { $post__in = implode(',', array_map('absint', $q['post__in'])); $where .= " AND {$wpdb->posts}.ID IN ({$post__in})"; } elseif ($q['post__not_in']) { $post__not_in = implode(',', array_map('absint', $q['post__not_in'])); $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})"; } if (is_numeric($q['post_parent'])) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']); } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $where = " AND {$wpdb->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { // added slashes screw with quote grouping when done early, so done later $q['s'] = stripslashes($q['s']); if (!empty($q['sentence'])) { $q['search_terms'] = array($q['s']); } else { preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches); $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]); } $n = !empty($q['exact']) ? '' : '%'; $searchand = ''; foreach ((array) $q['search_terms'] as $term) { $term = addslashes_gpc($term); $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))"; $searchand = ' AND '; } $term = $wpdb->escape($q['s']); if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) { $search .= " OR ({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')"; } if (!empty($search)) { $search = " AND ({$search}) "; } } // Category stuff if (empty($q['cat']) || $q['cat'] == '0' || $this->is_singular) { $whichcat = ''; } else { $q['cat'] = '' . urldecode($q['cat']) . ''; $q['cat'] = addslashes_gpc($q['cat']); $cat_array = preg_split('/[,\\s]+/', $q['cat']); $q['cat'] = ''; $req_cats = array(); foreach ((array) $cat_array as $cat) { $cat = intval($cat); $req_cats[] = $cat; $in = $cat > 0; $cat = abs($cat); if ($in) { $q['category__in'][] = $cat; $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category')); } else { $q['category__not_in'][] = $cat; $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category')); } } $q['cat'] = implode(',', $req_cats); } if (!empty($q['category__in'])) { $groupby = "{$wpdb->posts}.ID"; } if (!empty($q['category__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'category' "; $include_cats = "'" . implode("', '", $q['category__in']) . "'"; $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_cats}) "; } if (!empty($q['category__not_in'])) { if ($wpdb->has_cap('subqueries')) { $cat_string = "'" . implode("', '", $q['category__not_in']) . "'"; $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}) )"; } else { $ids = get_objects_in_term($q['category__not_in'], 'category'); if (is_wp_error($ids)) { $ids = array(); } if (is_array($ids) && count($ids > 0)) { $out_posts = "'" . implode("', '", $ids) . "'"; $whichcat .= " AND {$wpdb->posts}.ID NOT IN ({$out_posts})"; } } } // Category stuff for nice URLs if ('' != $q['category_name'] && !$this->is_singular) { $reqcat = get_category_by_path($q['category_name']); $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name']))); $cat_paths = '/' . trim($q['category_name'], '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = '/' . trim(urldecode($q['category_name']), '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = explode('/', $cat_paths); $cat_path = ''; foreach ((array) $cat_paths as $pathdir) { $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir); } //if we don't match the entire hierarchy fallback on just matching the nicename if (empty($reqcat)) { $reqcat = get_category_by_path($q['category_name'], false); } if (!empty($reqcat)) { $reqcat = $reqcat->term_id; } else { $reqcat = 0; } $q['cat'] = $reqcat; $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) "; $whichcat = " AND {$wpdb->term_taxonomy}.taxonomy = 'category' "; $in_cats = array($q['cat']); $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category')); $in_cats = "'" . implode("', '", $in_cats) . "'"; $whichcat .= "AND {$wpdb->term_taxonomy}.term_id IN ({$in_cats})"; $groupby = "{$wpdb->posts}.ID"; } // Tags if ('' != $q['tag']) { if (strpos($q['tag'], ',') !== false) { $tags = preg_split('/[,\\s]+/', $q['tag']); foreach ((array) $tags as $tag) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $tag; } } else { if (preg_match('/[+\\s]+/', $q['tag'])) { $tags = preg_split('/[+\\s]+/', $q['tag']); foreach ((array) $tags as $tag) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__and'][] = $tag; } } else { $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $q['tag']; } } } if (!empty($q['tag__in']) || !empty($q['tag_slug__in'])) { $groupby = "{$wpdb->posts}.ID"; } if (!empty($q['tag__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' "; $include_tags = "'" . implode("', '", $q['tag__in']) . "'"; $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_tags}) "; $reqtag = is_term($q['tag__in'][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } if (!empty($q['tag_slug__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' "; $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'"; $whichcat .= " AND {$wpdb->terms}.slug IN ({$include_tags}) "; $reqtag = get_term_by('slug', $q['tag_slug__in'][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag->term_id; } } if (!empty($q['tag__not_in'])) { if ($wpdb->has_cap('subqueries')) { $tag_string = "'" . implode("', '", $q['tag__not_in']) . "'"; $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}) )"; } else { $ids = get_objects_in_term($q['tag__not_in'], 'post_tag'); if (is_wp_error($ids)) { $ids = array(); } if (is_array($ids) && count($ids > 0)) { $out_posts = "'" . implode("', '", $ids) . "'"; $whichcat .= " AND {$wpdb->posts}.ID NOT IN ({$out_posts})"; } } } // Tag and slug intersections. $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag'); foreach ($intersections as $item => $taxonomy) { if (empty($q[$item])) { continue; } if ($item != 'category__and') { $reqtag = is_term($q[$item][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } $taxonomy_field = $item == 'tag_slug__and' ? 'slug' : 'term_id'; $q[$item] = array_unique($q[$item]); $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)"; $tsql .= " WHERE tt.taxonomy = '{$taxonomy}' AND t.{$taxonomy_field} IN ('" . implode("', '", $q[$item]) . "')"; $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]); $post_ids = $wpdb->get_col($tsql); if (count($post_ids)) { $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") "; } else { $whichcat = " AND 0 = 1"; break; } } // Taxonomies if ($this->is_tax) { if ('' != $q['taxonomy']) { $taxonomy = $q['taxonomy']; $tt[$taxonomy] = $q['term']; $terms = get_terms($q['taxonomy'], array('slug' => $q['term'])); } else { foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) { if (isset($t->query_var) && '' != $q[$t->query_var]) { $terms = get_terms($taxonomy, array('slug' => $q[$t->query_var])); if (!is_wp_error($terms)) { break; } } } } if (is_wp_error($terms) || empty($terms)) { $whichcat = " AND 0 "; } else { foreach ($terms as $term) { $term_ids[] = $term->term_id; } $post_ids = get_objects_in_term($term_ids, $taxonomy); if (!is_wp_error($post_ids) && count($post_ids)) { $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") "; $post_type = 'any'; $q['post_status'] = 'publish'; $post_status_join = true; } else { $whichcat = " AND 0 "; } } } // Author/user stuff if (empty($q['author']) || $q['author'] == '0') { $whichauthor = ''; } else { $q['author'] = '' . urldecode($q['author']) . ''; $q['author'] = addslashes_gpc($q['author']); if (strpos($q['author'], '-') !== false) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = '' . absint($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\\s]+/', $q['author']); $whichauthor .= " AND ({$wpdb->posts}.post_author " . $eq . ' ' . absint($author_array[0]); for ($i = 1; $i < count($author_array); $i = $i + 1) { $whichauthor .= ' ' . $andor . " {$wpdb->posts}.post_author " . $eq . ' ' . absint($author_array[$i]); } $whichauthor .= ')'; } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; #no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; #there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_nicename='" . $q['author_name'] . "'"); $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $whichmimetype = wp_post_mime_type_where($q['post_mime_type']); } $where .= $search . $whichcat . $whichauthor . $whichmimetype; if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') { $q['order'] = 'DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order']; } else { // Used to filter values $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand'); if (!empty($q['meta_key'])) { $allowed_keys[] = $q['meta_key']; $allowed_keys[] = 'meta_value'; } $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ', $q['orderby']); if (empty($orderby_array)) { $orderby_array[] = $q['orderby']; } $q['orderby'] = ''; for ($i = 0; $i < count($orderby_array); $i++) { // Only allow certain values for safety $orderby = $orderby_array[$i]; switch ($orderby) { case 'menu_order': break; case 'ID': $orderby = "{$wpdb->posts}.ID"; break; case 'rand': $orderby = 'RAND()'; break; case $q['meta_key']: case 'meta_value': $orderby = "{$wpdb->postmeta}.meta_value"; break; default: $orderby = "{$wpdb->posts}.post_" . $orderby; } if (in_array($orderby_array[$i], $allowed_keys)) { $q['orderby'] .= ($i == 0 ? '' : ',') . $orderby; } } // append ASC or DESC at the end if (!empty($q['orderby'])) { $q['orderby'] .= " {$q['order']}"; } if (empty($q['orderby'])) { $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order']; } } if ($this->is_attachment) { $where .= " AND {$wpdb->posts}.post_type = 'attachment'"; } elseif ($this->is_page) { $where .= " AND {$wpdb->posts}.post_type = 'page'"; } elseif ($this->is_single) { $where .= " AND {$wpdb->posts}.post_type = 'post'"; } elseif ('any' == $post_type) { $where .= ''; } else { $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'"; } if (isset($q['post_status']) && '' != $q['post_status']) { $statuswheres = array(); $q_status = explode(',', $q['post_status']); $r_status = array(); $p_status = array(); if (in_array('draft', $q_status)) { $r_status[] = "{$wpdb->posts}.post_status = 'draft'"; } if (in_array('pending', $q_status)) { $r_status[] = "{$wpdb->posts}.post_status = 'pending'"; } if (in_array('future', $q_status)) { $r_status[] = "{$wpdb->posts}.post_status = 'future'"; } if (in_array('inherit', $q_status)) { $r_status[] = "{$wpdb->posts}.post_status = 'inherit'"; } if (in_array('private', $q_status)) { $p_status[] = "{$wpdb->posts}.post_status = 'private'"; } if (in_array('publish', $q_status)) { $r_status[] = "{$wpdb->posts}.post_status = 'publish'"; } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can("edit_others_{$post_type}s")) { $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $r_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $r_status) . ")"; } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can("read_private_{$post_type}s")) { $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $p_status) . ")"; } } if ($post_status_join) { $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) "; foreach ($statuswheres as $index => $statuswhere) { $statuswheres[$index] = "({$statuswhere} OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; } } foreach ($statuswheres as $statuswhere) { $where .= " AND {$statuswhere}"; } } elseif (!$this->is_singular) { $where .= " AND ({$wpdb->posts}.post_status = 'publish'"; if (is_admin()) { $where .= " OR {$wpdb->posts}.post_status = 'future' OR {$wpdb->posts}.post_status = 'draft' OR {$wpdb->posts}.post_status = 'pending'"; } if (is_user_logged_in()) { $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'"; } $where .= ')'; } // postmeta queries if (!empty($q['meta_key']) || !empty($q['meta_value'])) { $join .= " LEFT JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) "; } if (!empty($q['meta_key'])) { $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s ", $q['meta_key']); } if (!empty($q['meta_value'])) { if (!isset($q['meta_compare']) || empty($q['meta_compare']) || !in_array($q['meta_compare'], array('=', '!=', '>', '>=', '<', '<='))) { $q['meta_compare'] = '='; } $where .= $wpdb->prepare("AND {$wpdb->postmeta}.meta_value {$q['meta_compare']} %s ", $q['meta_value']); } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. if (!$q['suppress_filters']) { $where = apply_filters('posts_where', $where); $join = apply_filters('posts_join', $join); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (empty($page)) { $page = 1; } if (empty($q['offset'])) { $pgstrt = ''; $pgstrt = ($page - 1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } } // Comments feeds if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) { if ($this->is_archive || $this->is_search) { $cjoin = "LEFT JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "GROUP BY {$wpdb->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "LEFT JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { $cjoin = apply_filters('comment_feed_join', $cjoin); $cwhere = apply_filters('comment_feed_where', $cwhere); $cgroupby = apply_filters('comment_feed_groupby', $cgroupby); } $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss')); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } $orderby = $q['orderby']; // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. if (!$q['suppress_filters']) { $where = apply_filters('posts_where_paged', $where); $groupby = apply_filters('posts_groupby', $groupby); $join = apply_filters('posts_join_paged', $join); $orderby = apply_filters('posts_orderby', $orderby); $distinct = apply_filters('posts_distinct', $distinct); $limits = apply_filters('post_limits', $limits); if (!empty($q['meta_key'])) { $fields = "{$fields}, {$wpdb->postmeta}.meta_value"; } $fields = apply_filters('posts_fields', $fields); } // Announce current selection parameters. For use by caching plugins. do_action('posts_selection', $where . $groupby . $orderby . $limits . $join); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if (!$q['suppress_filters']) { $where = apply_filters('posts_where_request', $where); $groupby = apply_filters('posts_groupby_request', $groupby); $join = apply_filters('posts_join_request', $join); $orderby = apply_filters('posts_orderby_request', $orderby); $distinct = apply_filters('posts_distinct_request', $distinct); $fields = apply_filters('posts_fields_request', $fields); $limits = apply_filters('post_limits_request', $limits); } if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } if (!empty($orderby)) { $orderby = 'ORDER BY ' . $orderby; } $found_rows = ''; if (!empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; if (!$q['suppress_filters']) { $this->request = apply_filters('posts_request', $this->request); } $this->posts = $wpdb->get_results($this->request); // Raw results filter. Prior to status checks. if (!$q['suppress_filters']) { $this->posts = apply_filters('posts_results', $this->posts); } if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) { $cjoin = apply_filters('comment_feed_join', ''); $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'"); $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss'); $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } if (!empty($limits)) { $found_posts_query = apply_filters('found_posts_query', 'SELECT FOUND_ROWS()'); $this->found_posts = $wpdb->get_var($found_posts_query); $this->found_posts = apply_filters('found_posts', $this->found_posts); $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); //$type = get_post_type($this->posts[0]); if ('publish' != $status) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if (in_array($status, array('draft', 'pending'))) { // User must have edit permissions on the draft to preview. if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; $this->posts[0]->post_date = current_time('mysql'); } } else { if ('future' == $status) { $this->is_preview = true; if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } } else { if (!current_user_can('read_post', $this->posts[0]->ID)) { $this->posts = array(); } } } } } if ($this->is_preview && current_user_can("edit_{$post_type}", $this->posts[0]->ID)) { $this->posts[0] = apply_filters('the_preview', $this->posts[0]); } } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ($this->is_home && $page <= 1 && !empty($sticky_posts) && !$q['caller_get_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); array_splice($sticky_posts, $offset, 1); } } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies__in = implode(',', array_map('absint', $sticky_posts)); $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in})"); /** @todo Make sure post is published or viewable by the current user */ foreach ($stickies as $sticky_post) { if ('publish' != $sticky_post->post_status) { continue; } array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } if (!$q['suppress_filters']) { $this->posts = apply_filters('the_posts', $this->posts); } update_post_caches($this->posts); $this->post_count = count($this->posts); if ($this->post_count > 0) { $this->post = $this->posts[0]; } return $this->posts; }
function get_posts() { global $wpdb, $pagenow, $request, $user_ID; // Shorthand. $q = $this->query_vars; // First let's clear some variables $whichcat = ''; $whichauthor = ''; $result = ''; $where = ''; $limits = ''; $distinct = ''; $join = ''; if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 ) $q['posts_per_page'] = get_settings('posts_per_page'); if ( !isset($q['what_to_show']) ) $q['what_to_show'] = get_settings('what_to_show'); if ( isset($q['showposts']) && $q['showposts'] ) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) ) $q['posts_per_page'] = $q['posts_per_archive_page']; if ( !isset($q['nopaging']) ) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ( $this->is_feed ) $q['posts_per_page'] = get_settings('posts_per_rss'); $add_hours = intval(get_settings('gmt_offset')); $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours)); $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"; // If a month is specified in the querystring, load that month if ( (int) $q['m'] ) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4); if (strlen($q['m'])>5) $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2); if (strlen($q['m'])>7) $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2); if (strlen($q['m'])>9) $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2); if (strlen($q['m'])>11) $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2); if (strlen($q['m'])>13) $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2); } if ( (int) $q['hour'] ) { $q['hour'] = '' . intval($q['hour']); $where .= " AND HOUR(post_date)='" . $q['hour'] . "'"; } if ( (int) $q['minute'] ) { $q['minute'] = '' . intval($q['minute']); $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'"; } if ( (int) $q['second'] ) { $q['second'] = '' . intval($q['second']); $where .= " AND SECOND(post_date)='" . $q['second'] . "'"; } if ( (int) $q['year'] ) { $q['year'] = '' . intval($q['year']); $where .= " AND YEAR(post_date)='" . $q['year'] . "'"; } if ( (int) $q['monthnum'] ) { $q['monthnum'] = '' . intval($q['monthnum']); $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'"; } if ( (int) $q['day'] ) { $q['day'] = '' . intval($q['day']); $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'"; } if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND post_name = '" . $q['name'] . "'"; } else if ('' != $q['pagename']) { $q['pagename'] = sanitize_title(basename(str_replace('%2F', '/', urlencode($q['pagename'])))); $q['name'] = $q['pagename']; $where .= " AND post_name = '" . $q['pagename'] . "'"; } if ( (int) $q['w'] ) { $q['w'] = ''.intval($q['w']); $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'"; } if ( intval($q['comments_popup']) ) $q['p'] = intval($q['comments_popup']); // If a post number is specified, load that post if (($q['p'] != '') && intval($q['p']) != 0) { $q['p'] = (int) $q['p']; $where = ' AND ID = ' . $q['p']; } if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) { $q['page_id'] = intval($q['page_id']); $q['p'] = $q['page_id']; $where = ' AND ID = '.$q['page_id']; } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { $q['s'] = addslashes_gpc($q['s']); $search = ' AND ('; $q['s'] = preg_replace('/, +/', ' ', $q['s']); $q['s'] = str_replace(',', ' ', $q['s']); $q['s'] = str_replace('"', ' ', $q['s']); $q['s'] = trim($q['s']); if ($q['exact']) { $n = ''; } else { $n = '%'; } if (!$q['sentence']) { $s_array = explode(' ',$q['s']); $q['search_terms'] = $s_array; $search .= '((post_title LIKE \''.$n.$s_array[0].$n.'\') OR (post_content LIKE \''.$n.$s_array[0].$n.'\'))'; for ( $i = 1; $i < count($s_array); $i = $i + 1) { $search .= ' AND ((post_title LIKE \''.$n.$s_array[$i].$n.'\') OR (post_content LIKE \''.$n.$s_array[$i].$n.'\'))'; } $search .= ' OR (post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\')'; $search .= ')'; } else { $search = ' AND ((post_title LIKE \''.$n.$q['s'].$n.'\') OR (post_content LIKE \''.$n.$q['s'].$n.'\'))'; } } // Category stuff if ((empty($q['cat'])) || ($q['cat'] == '0') || // Bypass cat checks if fetching specific posts ( $this->is_single || $this->is_page )) { $whichcat=''; } else { $q['cat'] = ''.urldecode($q['cat']).''; $q['cat'] = addslashes_gpc($q['cat']); if (stristr($q['cat'],'-')) { // Note: if we have a negative, we ignore all the positives. It must // always mean 'everything /except/ this one'. We should be able to do // multiple negatives but we don't :-( $eq = '!='; $andor = 'AND'; $q['cat'] = explode('-',$q['cat']); $q['cat'] = intval($q['cat'][1]); } else { $eq = '='; $andor = 'OR'; } $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) "; $cat_array = preg_split('/[,\s]+/', $q['cat']); $whichcat .= ' AND (category_id '.$eq.' '.intval($cat_array[0]); $whichcat .= get_category_children($cat_array[0], ' '.$andor.' category_id '.$eq.' '); for ($i = 1; $i < (count($cat_array)); $i = $i + 1) { $whichcat .= ' '.$andor.' category_id '.$eq.' '.intval($cat_array[$i]); $whichcat .= get_category_children($cat_array[$i], ' '.$andor.' category_id '.$eq.' '); } $whichcat .= ')'; if ($eq == '!=') { $q['cat'] = '-'.$q['cat']; // Put back the knowledge that we are excluding a category. } } // Category stuff for nice URIs if ('' != $q['category_name']) { if (stristr($q['category_name'],'/')) { $q['category_name'] = explode('/',$q['category_name']); if ($q['category_name'][count($q['category_name'])-1]) { $q['category_name'] = $q['category_name'][count($q['category_name'])-1]; // no trailing slash } else { $q['category_name'] = $q['category_name'][count($q['category_name'])-2]; // there was a trailling slash } } $q['category_name'] = sanitize_title($q['category_name']); $tables = ", $wpdb->post2cat, $wpdb->categories"; $join = " LEFT JOIN $wpdb->post2cat ON ($wpdb->posts.ID = $wpdb->post2cat.post_id) LEFT JOIN $wpdb->categories ON ($wpdb->post2cat.category_id = $wpdb->categories.cat_ID) "; $whichcat = " AND (category_nicename = '" . $q['category_name'] . "'"; $q['cat'] = $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE category_nicename = '" . $q['category_name'] . "'"); $whichcat .= get_category_children($q['cat'], " OR category_id = "); $whichcat .= ")"; } // Author/user stuff if ((empty($q['author'])) || ($q['author'] == '0')) { $whichauthor=''; } else { $q['author'] = ''.urldecode($q['author']).''; $q['author'] = addslashes_gpc($q['author']); if (stristr($q['author'], '-')) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = ''.intval($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\s]+/', $q['author']); $whichauthor .= ' AND (post_author '.$eq.' '.intval($author_array[0]); for ($i = 1; $i < (count($author_array)); $i = $i + 1) { $whichauthor .= ' '.$andor.' post_author '.$eq.' '.intval($author_array[$i]); } $whichauthor .= ')'; } // Author stuff for nice URIs if ('' != $q['author_name']) { if (stristr($q['author_name'],'/')) { $q['author_name'] = explode('/',$q['author_name']); if ($q['author_name'][count($q['author_name'])-1]) { $q['author_name'] = $q['author_name'][count($q['author_name'])-1];#no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name'])-2];#there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = $wpdb->get_var("SELECT ID FROM $wpdb->users WHERE user_nicename='".$q['author_name']."'"); $whichauthor .= ' AND (post_author = '.intval($q['author']).')'; } $where .= $search.$whichcat.$whichauthor; if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) { $q['order']='DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby']='date '.$q['order']; } else { // Used to filter values $allowed_keys = array('author','date','category','title'); $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ',$q['orderby']); if (!in_array($orderby_array[0],$allowed_keys)) { $orderby_array[0] = 'date'; } $q['orderby'] = $orderby_array[0].' '.$q['order']; if (count($orderby_array)>1) { for ($i = 1; $i < (count($orderby_array)); $i = $i + 1) { // Only allow certain values for safety if (in_array($orderby_array[$i],$allowed_keys)) { $q['orderby'] .= ',post_'.$orderby_array[$i].' '.$q['order']; } } } } $now = gmdate('Y-m-d H:i:59'); if ($pagenow != 'post.php' && $pagenow != 'edit.php') { $where .= " AND post_date_gmt <= '$now'"; $distinct = 'DISTINCT'; } if ($this->is_page) { $where .= ' AND (post_status = "static"'; } else { $where .= ' AND (post_status = "publish"'; } // Get private posts if (isset($user_ID) && ('' != intval($user_ID))) $where .= " OR post_author = $user_ID AND post_status != 'draft' AND post_status != 'static')"; else $where .= ')'; // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. $where = apply_filters('posts_where', $where); $join = apply_filters('posts_join', $join); // Paging if (empty($q['nopaging']) && ! $this->is_single) { $page = $q['paged']; if (empty($page)) { $page = 1; } if (($q['what_to_show'] == 'posts')) { $pgstrt = ''; $pgstrt = (intval($page) -1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT '.$pgstrt.$q['posts_per_page']; } elseif ($q['what_to_show'] == 'days') { $startrow = $q['posts_per_page'] * (intval($page)-1); $start_date = $wpdb->get_var("SELECT max(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $startrow,1"); $endrow = $startrow + $q['posts_per_page'] - 1; $end_date = $wpdb->get_var("SELECT min(post_date) FROM $wpdb->posts $join WHERE (1=1) $where GROUP BY year(post_date), month(post_date), dayofmonth(post_date) ORDER BY post_date DESC LIMIT $endrow,1"); if ($page > 1) { $where .= " AND post_date >= '$end_date' AND post_date <= '$start_date'"; } else { $where .= " AND post_date >= '$end_date'"; } } } // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. $where = apply_filters('posts_where_paged', $where); $where .= " GROUP BY $wpdb->posts.ID"; $join = apply_filters('posts_join_paged', $join); $request = " SELECT $distinct * FROM $wpdb->posts $join WHERE 1=1".$where." ORDER BY post_" . $q['orderby'] . " $limits"; if ($q['preview']) { $request = 'SELECT 1-1'; // dummy mysql query for the preview // little funky fix for IEwin, rawk on that code $is_winIE = ((preg_match('/MSIE/',$HTTP_USER_AGENT)) && (preg_match('/Win/',$HTTP_USER_AGENT))); if (($is_winIE) && (!isset($IEWin_bookmarklet_fix))) { $preview_content = preg_replace('/\%u([0-9A-F]{4,4})/e', "'&#'.base_convert('\\1',16,10).';'", $preview_content); } } $this->posts = $wpdb->get_results($request); $this->posts = apply_filters('the_posts', $this->posts); $this->post_count = count($this->posts); if ($this->post_count > 0) { $this->post = $this->posts[0]; } update_post_caches($this->posts); // Save any changes made to the query vars. $this->query_vars = $q; return $this->posts; }
function get_posts($args) { global $wpdb; parse_str($args, $r); if ( !isset($r['numberposts']) ) $r['numberposts'] = 5; if ( !isset($r['offset']) ) $r['offset'] = 0; if ( !isset($r['category']) ) $r['category'] = ''; if ( !isset($r['orderby']) ) $r['orderby'] = 'post_date'; if ( !isset($r['order']) ) $r['order'] = 'DESC'; $now = current_time('mysql'); $posts = $wpdb->get_results( "SELECT DISTINCT * FROM $wpdb->posts " . ( empty( $r['category'] ) ? "" : ", $wpdb->post2cat " ) . " WHERE post_date <= '$now' AND (post_status = 'publish') ". ( empty( $r['category'] ) ? "" : "AND $wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $r['category']. " " ) . " GROUP BY $wpdb->posts.ID ORDER BY " . $r['orderby'] . " " . $r['order'] . " LIMIT " . $r['offset'] . ',' . $r['numberposts'] ); update_post_caches($posts); return $posts; }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @return array List of posts. */ function &get_posts() { global $wpdb, $user_ID, $_wp_using_ext_object_cache; do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; $q = $this->fill_query_vars($q); // First let's clear some variables $distinct = ''; $whichcat = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $fields = "{$wpdb->posts}.*"; $post_status_join = false; $page = 1; if (!isset($q['caller_get_posts'])) { $q['caller_get_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['cache_results'])) { if ($_wp_using_ext_object_cache) { $q['cache_results'] = false; } else { $q['cache_results'] = true; } } if (!isset($q['update_post_term_cache'])) { $q['update_post_term_cache'] = true; } if (!isset($q['update_post_meta_cache'])) { $q['update_post_meta_cache'] = true; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = ''; } } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present. if (isset($q['no_found_rows'])) { $q['no_found_rows'] = (bool) $q['no_found_rows']; } else { $q['no_found_rows'] = false; } // If a month is specified in the querystring, load that month if ($q['m']) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2); } } if ('' !== $q['hour']) { $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'"; } if ('' !== $q['minute']) { $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'"; } if ('' !== $q['second']) { $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'"; } if ($q['year']) { $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'"; } if ($q['monthnum']) { $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'"; } if ($q['day']) { $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'"; } // If we've got a post_type AND its not "any" post_type. if (!empty($q['post_type']) && 'any' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) { continue; } if (!$ptype_obj->hierarchical || strpos($q[$ptype_obj->query_var], '/') === false) { // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name' $q['name'] = $q[$ptype_obj->query_var]; } else { // Hierarchical post_types will operate through the $q['pagename'] = $q[$ptype_obj->query_var]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'"; } elseif ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { if ('page' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->hierarchical) { continue; } $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ($reqpage) { break; } } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename']))); $page_paths = '/' . trim($q['pagename'], '/'); $q['pagename'] = sanitize_title(basename($page_paths)); $q['name'] = $q['pagename']; $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')"; $reqpage_obj = get_page($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment']))); $attach_paths = '/' . trim($q['attachment'], '/'); $q['attachment'] = sanitize_title(basename($attach_paths)); $q['name'] = $q['attachment']; $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'"; } if ($q['w']) { $where .= ' AND ' . _wp_mysql_week("`{$wpdb->posts}`.`post_date`") . " = '" . $q['w'] . "'"; } if (intval($q['comments_popup'])) { $q['p'] = absint($q['comments_popup']); } // If an attachment is requested by number, let it supercede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $where .= " AND {$wpdb->posts}.ID = " . $q['p']; } elseif ($q['post__in']) { $post__in = implode(',', array_map('absint', $q['post__in'])); $where .= " AND {$wpdb->posts}.ID IN ({$post__in})"; } elseif ($q['post__not_in']) { $post__not_in = implode(',', array_map('absint', $q['post__not_in'])); $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})"; } if (is_numeric($q['post_parent'])) { $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']); } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $where = " AND {$wpdb->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { // added slashes screw with quote grouping when done early, so done later $q['s'] = stripslashes($q['s']); if (!empty($q['sentence'])) { $q['search_terms'] = array($q['s']); } else { preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q['s'], $matches); $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]); } $n = !empty($q['exact']) ? '' : '%'; $searchand = ''; foreach ((array) $q['search_terms'] as $term) { $term = addslashes_gpc($term); $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))"; $searchand = ' AND '; } $term = esc_sql($q['s']); if (empty($q['sentence']) && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) { $search .= " OR ({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}')"; } if (!empty($search)) { $search = " AND ({$search}) "; if (!is_user_logged_in()) { $search .= " AND ({$wpdb->posts}.post_password = '') "; } } } // Allow plugins to contextually add/remove/modify the search section of the database query $search = apply_filters_ref_array('posts_search', array($search, &$this)); // Category stuff if (empty($q['cat']) || $q['cat'] == '0' || $this->is_singular) { $whichcat = ''; } else { $q['cat'] = '' . urldecode($q['cat']) . ''; $q['cat'] = addslashes_gpc($q['cat']); $cat_array = preg_split('/[,\\s]+/', $q['cat']); $q['cat'] = ''; $req_cats = array(); foreach ((array) $cat_array as $cat) { $cat = intval($cat); $req_cats[] = $cat; $in = $cat > 0; $cat = abs($cat); if ($in) { $q['category__in'][] = $cat; $q['category__in'] = array_merge($q['category__in'], get_term_children($cat, 'category')); } else { $q['category__not_in'][] = $cat; $q['category__not_in'] = array_merge($q['category__not_in'], get_term_children($cat, 'category')); } } $q['cat'] = implode(',', $req_cats); } if (!empty($q['category__in'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'category' "; $include_cats = "'" . implode("', '", $q['category__in']) . "'"; $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_cats}) "; } if (!empty($q['category__not_in'])) { $cat_string = "'" . implode("', '", $q['category__not_in']) . "'"; $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}) )"; } // Category stuff for nice URLs if ('' != $q['category_name'] && !$this->is_singular) { $q['category_name'] = implode('/', array_map('sanitize_title', explode('/', $q['category_name']))); $reqcat = get_category_by_path($q['category_name']); $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name']))); $cat_paths = '/' . trim($q['category_name'], '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = '/' . trim(urldecode($q['category_name']), '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = explode('/', $cat_paths); $cat_path = ''; foreach ((array) $cat_paths as $pathdir) { $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir); } //if we don't match the entire hierarchy fallback on just matching the nicename if (empty($reqcat)) { $reqcat = get_category_by_path($q['category_name'], false); } if (!empty($reqcat)) { $reqcat = $reqcat->term_id; } else { $reqcat = 0; } $q['cat'] = $reqcat; $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) "; $whichcat = " AND {$wpdb->term_taxonomy}.taxonomy = 'category' "; $in_cats = array($q['cat']); $in_cats = array_merge($in_cats, get_term_children($q['cat'], 'category')); $in_cats = "'" . implode("', '", $in_cats) . "'"; $whichcat .= "AND {$wpdb->term_taxonomy}.term_id IN ({$in_cats})"; $groupby = "{$wpdb->posts}.ID"; } // Tags if ('' != $q['tag']) { if (strpos($q['tag'], ',') !== false) { $tags = preg_split('/[,\\s]+/', $q['tag']); foreach ((array) $tags as $tag) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $tag; } } else { if (preg_match('/[+\\s]+/', $q['tag']) || !empty($q['cat'])) { $tags = preg_split('/[+\\s]+/', $q['tag']); foreach ((array) $tags as $tag) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__and'][] = $tag; } } else { $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $q['tag']; } } } if (!empty($q['category__in']) || !empty($q['meta_key']) || !empty($q['tag__in']) || !empty($q['tag_slug__in'])) { $groupby = "{$wpdb->posts}.ID"; } if (!empty($q['tag__in']) && empty($q['cat'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' "; $include_tags = "'" . implode("', '", $q['tag__in']) . "'"; $whichcat .= " AND {$wpdb->term_taxonomy}.term_id IN ({$include_tags}) "; $reqtag = term_exists($q['tag__in'][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } if (!empty($q['tag_slug__in']) && empty($q['cat'])) { $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) "; $whichcat .= " AND {$wpdb->term_taxonomy}.taxonomy = 'post_tag' "; $include_tags = "'" . implode("', '", $q['tag_slug__in']) . "'"; $whichcat .= " AND {$wpdb->terms}.slug IN ({$include_tags}) "; $reqtag = get_term_by('slug', $q['tag_slug__in'][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag->term_id; } } if (!empty($q['tag__not_in'])) { $tag_string = "'" . implode("', '", $q['tag__not_in']) . "'"; $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}) )"; } // Tag and slug intersections. $intersections = array('category__and' => 'category', 'tag__and' => 'post_tag', 'tag_slug__and' => 'post_tag', 'tag__in' => 'post_tag', 'tag_slug__in' => 'post_tag'); $tagin = array('tag__in', 'tag_slug__in'); // These are used to make some exceptions below foreach ($intersections as $item => $taxonomy) { if (empty($q[$item])) { continue; } if (in_array($item, $tagin) && empty($q['cat'])) { continue; } // We should already have what we need if categories aren't being used if ($item != 'category__and') { $reqtag = term_exists($q[$item][0], 'post_tag'); if (!empty($reqtag)) { $q['tag_id'] = $reqtag['term_id']; } } if (in_array($item, array('tag_slug__and', 'tag_slug__in'))) { $taxonomy_field = 'slug'; } else { $taxonomy_field = 'term_id'; } $q[$item] = array_unique($q[$item]); $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)"; $tsql .= " WHERE tt.taxonomy = '{$taxonomy}' AND t.{$taxonomy_field} IN ('" . implode("', '", $q[$item]) . "')"; if (!in_array($item, $tagin)) { // This next line is only helpful if we are doing an and relationship $tsql .= " GROUP BY p.ID HAVING count(p.ID) = " . count($q[$item]); } $post_ids = $wpdb->get_col($tsql); if (count($post_ids)) { $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") "; } else { $whichcat = " AND 0 = 1"; break; } } // Taxonomies if ($this->is_tax) { if ('' != $q['taxonomy']) { $taxonomy = $q['taxonomy']; $tt[$taxonomy] = $q['term']; } else { foreach ($GLOBALS['wp_taxonomies'] as $taxonomy => $t) { if ($t->query_var && '' != $q[$t->query_var]) { $tt[$taxonomy] = $q[$t->query_var]; break; } } } $terms = get_terms($taxonomy, array('slug' => $tt[$taxonomy], 'hide_empty' => !is_taxonomy_hierarchical($taxonomy))); if (is_wp_error($terms) || empty($terms)) { $whichcat = " AND 0 "; } else { foreach ($terms as $term) { $term_ids[] = $term->term_id; if (is_taxonomy_hierarchical($taxonomy)) { $children = get_term_children($term->term_id, $taxonomy); $term_ids = array_merge($term_ids, $children); } } $post_ids = get_objects_in_term($term_ids, $taxonomy); if (!is_wp_error($post_ids) && !empty($post_ids)) { $whichcat .= " AND {$wpdb->posts}.ID IN (" . implode(', ', $post_ids) . ") "; if (empty($post_type)) { $post_type = 'any'; $post_status_join = true; } elseif (in_array('attachment', (array) $post_type)) { $post_status_join = true; } } else { $whichcat = " AND 0 "; } } } // Author/user stuff if (empty($q['author']) || $q['author'] == '0') { $whichauthor = ''; } else { $q['author'] = (string) urldecode($q['author']); $q['author'] = addslashes_gpc($q['author']); if (strpos($q['author'], '-') !== false) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = (string) absint($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\\s]+/', $q['author']); $_author_array = array(); foreach ($author_array as $key => $_author) { $_author_array[] = "{$wpdb->posts}.post_author " . $eq . ' ' . absint($_author); } $whichauthor .= ' AND (' . implode(" {$andor} ", $_author_array) . ')'; unset($author_array, $_author_array); } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; // there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = get_user_by('slug', $q['author_name']); if ($q['author']) { $q['author'] = $q['author']->ID; } $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $table_alias = $post_status_join ? $wpdb->posts : ''; $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $table_alias); } $where .= $search . $whichcat . $whichauthor . $whichmimetype; if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') { $q['order'] = 'DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order']; } elseif ('none' == $q['orderby']) { $q['orderby'] = ''; } else { // Used to filter values $allowed_keys = array('author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count'); if (!empty($q['meta_key'])) { $allowed_keys[] = $q['meta_key']; $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; } $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ', $q['orderby']); $q['orderby'] = ''; foreach ($orderby_array as $i => $orderby) { // Only allow certain values for safety if (!in_array($orderby, $allowed_keys)) { continue; } switch ($orderby) { case 'menu_order': break; case 'ID': $orderby = "{$wpdb->posts}.ID"; break; case 'rand': $orderby = 'RAND()'; break; case $q['meta_key']: case 'meta_value': $orderby = "{$wpdb->postmeta}.meta_value"; break; case 'meta_value_num': $orderby = "{$wpdb->postmeta}.meta_value+0"; break; case 'comment_count': $orderby = "{$wpdb->posts}.comment_count"; break; default: $orderby = "{$wpdb->posts}.post_" . $orderby; } $q['orderby'] .= ($i == 0 ? '' : ',') . $orderby; } // append ASC or DESC at the end if (!empty($q['orderby'])) { $q['orderby'] .= " {$q['order']}"; } if (empty($q['orderby'])) { $q['orderby'] = "{$wpdb->posts}.post_date " . $q['order']; } } if (is_array($post_type)) { $post_type_cap = 'multiple_post_type'; } else { $post_type_object = get_post_type_object($post_type); if (!empty($post_type_object)) { $post_type_cap = $post_type_object->capability_type; } else { $post_type_cap = $post_type; } } $exclude_post_types = ''; $in_search_post_types = get_post_types(array('exclude_from_search' => false)); if (!empty($in_search_post_types)) { $exclude_post_types .= $wpdb->prepare(" AND {$wpdb->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')"); } if ('any' == $post_type) { $where .= $exclude_post_types; } elseif (!empty($post_type) && is_array($post_type)) { $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", $post_type) . "')"; } elseif (!empty($post_type)) { $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'"; $post_type_object = get_post_type_object($post_type); } elseif ($this->is_attachment) { $where .= " AND {$wpdb->posts}.post_type = 'attachment'"; $post_type_object = get_post_type_object('attachment'); } elseif ($this->is_page) { $where .= " AND {$wpdb->posts}.post_type = 'page'"; $post_type_object = get_post_type_object('page'); } else { $where .= " AND {$wpdb->posts}.post_type = 'post'"; $post_type_object = get_post_type_object('post'); } if (!empty($post_type_object)) { $post_type_cap = $post_type_object->capability_type; $edit_cap = $post_type_object->cap->edit_post; $read_cap = $post_type_object->cap->read_post; $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_cap = 'edit_' . $post_type_cap; $read_cap = 'read_' . $post_type_cap; $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } if (isset($q['post_status']) && '' != $q['post_status']) { $statuswheres = array(); $q_status = explode(',', $q['post_status']); $r_status = array(); $p_status = array(); $e_status = array(); if ($q['post_status'] == 'any') { foreach (get_post_stati(array('exclude_from_search' => true)) as $status) { $e_status[] = "{$wpdb->posts}.post_status <> '{$status}'"; } } else { foreach (get_post_stati() as $status) { if (in_array($status, $q_status)) { if ('private' == $status) { $p_status[] = "{$wpdb->posts}.post_status = '{$status}'"; } else { $r_status[] = "{$wpdb->posts}.post_status = '{$status}'"; } } } } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($e_status)) { $statuswheres[] = "(" . join(' AND ', $e_status) . ")"; } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) { $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $r_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $r_status) . ")"; } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) { $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $p_status) . ")"; } } if ($post_status_join) { $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) "; foreach ($statuswheres as $index => $statuswhere) { $statuswheres[$index] = "({$statuswhere} OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; } } foreach ($statuswheres as $statuswhere) { $where .= " AND {$statuswhere}"; } } elseif (!$this->is_singular) { $where .= " AND ({$wpdb->posts}.post_status = 'publish'"; // Add public states. $public_states = get_post_stati(array('public' => true)); foreach ((array) $public_states as $state) { if ('publish' == $state) { // Publish is hard-coded above. continue; } $where .= " OR {$wpdb->posts}.post_status = '{$state}'"; } if (is_admin()) { // Add protected states that should show in the admin all list. $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true)); foreach ((array) $admin_all_states as $state) { $where .= " OR {$wpdb->posts}.post_status = '{$state}'"; } } if (is_user_logged_in()) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati(array('private' => true)); foreach ((array) $private_states as $state) { $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}'"; } } $where .= ')'; } // postmeta queries if (!empty($q['meta_key']) || !empty($q['meta_value'])) { $join .= " JOIN {$wpdb->postmeta} ON ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id) "; } if (!empty($q['meta_key'])) { $where .= $wpdb->prepare(" AND {$wpdb->postmeta}.meta_key = %s ", $q['meta_key']); } if (!empty($q['meta_value'])) { if (empty($q['meta_compare']) || !in_array($q['meta_compare'], array('=', '!=', '>', '>=', '<', '<='))) { $q['meta_compare'] = '='; } $where .= $wpdb->prepare("AND {$wpdb->postmeta}.meta_value {$q['meta_compare']} %s ", $q['meta_value']); } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. if (!$q['suppress_filters']) { $where = apply_filters_ref_array('posts_where', array($where, &$this)); $join = apply_filters_ref_array('posts_join', array($join, &$this)); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (empty($page)) { $page = 1; } if (empty($q['offset'])) { $pgstrt = ''; $pgstrt = ($page - 1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } } // Comments feeds if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) { if ($this->is_archive || $this->is_search) { $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "{$wpdb->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this)); $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this)); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this)); $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); } $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } $orderby = $q['orderby']; // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. if (!$q['suppress_filters']) { $where = apply_filters_ref_array('posts_where_paged', array($where, &$this)); $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this)); $join = apply_filters_ref_array('posts_join_paged', array($join, &$this)); $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this)); $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this)); $limits = apply_filters_ref_array('post_limits', array($limits, &$this)); $fields = apply_filters_ref_array('posts_fields', array($fields, &$this)); } // Announce current selection parameters. For use by caching plugins. do_action('posts_selection', $where . $groupby . $orderby . $limits . $join); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if (!$q['suppress_filters']) { $where = apply_filters_ref_array('posts_where_request', array($where, &$this)); $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this)); $join = apply_filters_ref_array('posts_join_request', array($join, &$this)); $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this)); $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this)); $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this)); $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this)); } if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } if (!empty($orderby)) { $orderby = 'ORDER BY ' . $orderby; } $found_rows = ''; if (!$q['no_found_rows'] && !empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; if (!$q['suppress_filters']) { $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this)); } $this->posts = $wpdb->get_results($this->request); // Raw results filter. Prior to status checks. if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this)); } if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) { $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this)); $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this)); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this)); $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"; $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } if (!$q['no_found_rows'] && !empty($limits)) { $found_posts_query = apply_filters_ref_array('found_posts_query', array('SELECT FOUND_ROWS()', &$this)); $this->found_posts = $wpdb->get_var($found_posts_query); $this->found_posts = apply_filters_ref_array('found_posts', array($this->found_posts, &$this)); $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); $post_status_obj = get_post_status_object($status); //$type = get_post_type($this->posts[0]); if (!$post_status_obj->public) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ($post_status_obj->protected) { // User must have edit permissions on the draft to preview. if (!current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; if ('future' != $status) { $this->posts[0]->post_date = current_time('mysql'); } } } elseif ($post_status_obj->private) { if (!current_user_can($read_cap, $this->posts[0]->ID)) { $this->posts = array(); } } else { $this->posts = array(); } } } if ($this->is_preview && current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts[0] = apply_filters_ref_array('the_preview', array($this->posts[0], &$this)); } } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['caller_get_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset($sticky_posts[$offset]); } } // If any posts have been excluded specifically, Ignore those that are sticky. if (!empty($sticky_posts) && !empty($q['post__not_in'])) { $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies__in = implode(',', array_map('absint', $sticky_posts)); // honor post type(s) if not set to any $stickies_where = ''; if ('any' != $post_type && '' != $post_type) { if (is_array($post_type)) { $post_types = join("', '", $post_type); } else { $post_types = $post_type; } $stickies_where = "AND {$wpdb->posts}.post_type IN ('" . $post_types . "')"; } $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in}) {$stickies_where}"); foreach ($stickies as $sticky_post) { // Ignore sticky posts the current user cannot read or are not published. if ('publish' != $sticky_post->post_status) { continue; } array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } if (!$q['suppress_filters']) { $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this)); } $this->post_count = count($this->posts); // Sanitize before caching so it'll only get done once for ($i = 0; $i < $this->post_count; $i++) { $this->posts[$i] = sanitize_post($this->posts[$i], 'raw'); } if ($q['cache_results']) { update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); } if ($this->post_count > 0) { $this->post = $this->posts[0]; } return $this->posts; }
function sb_cl_render_cat_list($category, $limit = false, $order = false, $template_id = 0, $thumb_size = false) { global $wp_query, $posts; $settings = sb_cl_get_settings(); if (!$limit) { $limit = 1000; } if (!$thumb_size) { $thumb_size = 'thumb'; } if (!trim($order)) { $order = 'post_title'; } if ($template_id <= 1) { $template_start = $settings->cat_list_start; $template_loop = $settings->cat_list_loop; $template_end = $settings->cat_list_end; } else { $func = 'cat_list_start_' . $template_id; $template_start = $settings->{$func}; $func = 'cat_list_loop_' . $template_id; $template_loop = $settings->{$func}; $func = 'cat_list_end_' . $template_id; $template_end = $settings->{$func}; } $temp_query = $wp_query; $cat_id = sb_cl_get_cat_id_from_name($category); $qs = "cat=" . $cat_id . '&post_status=publish'; $qs .= '&posts_per_page=' . $limit; $qs .= '&orderby=' . $order; $cat_posts = new WP_Query($qs); $html .= $template_start; while ($cat_posts->have_posts()) { $cat_posts->the_post(); update_post_caches($posts); $id = get_the_ID(); ob_start(); the_permalink(); $permalink = ob_get_clean(); $template = $template_loop; $template = str_replace('[post_title]', get_the_title(), $template); $template = str_replace('[post_excerpt]', sb_cl_get_the_excerpt(), $template); $template = str_replace('[post_permalink]', $permalink, $template); $post_image = get_post_meta($id, 'post_image', true); $post_image2 = get_post_meta($id, 'post_image2', true); $template = str_replace('[post_image]', $post_image ? '<img class="list_post_item" src="' . $post_image . '" />' : '', $template); $template = str_replace('[post_image2]', $post_image2 ? '<img class="list_post_item" src="' . $post_image2 . '" />' : '', $template); if (function_exists('get_the_post_thumbnail')) { //$template = str_replace('[post_thumb]', get_the_post_thumbnail( $id, 'thumbnail', array('class' => 'alignleft')), $template); $thumb = $large_image_url = ''; if (has_post_thumbnail()) { $large_image_url = wp_get_attachment_image_src(get_post_thumbnail_id($id), 'large'); $thumb .= get_the_post_thumbnail($id, $thumb_size, array('class' => 'alignleft')); } $template = str_replace('[post_thumb]', $thumb, $template); $template = str_replace('[post_thumb_url]', $large_image_url, $template); } $html .= $template; } $html .= $template_end; $wp_query = $temp_query; rewind_posts(); the_post(); return $html; }
/** * How to display the widget on the screen. */ function widget($args, $instance) { extract($args); /* Our variables from the widget settings. */ $title = apply_filters('widget_title', $instance['title']); $category_id = $instance['category_id']; $num_posts = absint($instance['num_posts']); $post_offset = absint($instance['post_offset']); $num_words_limit = absint($instance['num_words_limit']); $show_date_author = isset($instance['show_date_author']) ? $instance['show_date_author'] : false; $show_more_link = isset($instance['show_more_link']) ? $instance['show_more_link'] : false; $show_thumbs = isset($instance['show_thumbs']) ? $instance['show_thumbs'] : false; $thumb_frame_shadow = isset($instance['thumb_frame_shadow']) ? $instance['thumb_frame_shadow'] : false; $post_thumb_width = absint($instance['post_thumb_width']); $post_thumb_height = absint($instance['post_thumb_height']); /* Before widget (defined by themes). */ echo $before_widget; /* Display the widget title if one was input (before and after defined by themes). */ if ($title) { echo $before_title . $title . $after_title; } /* Display the Latest Posts accordinly... */ $cats_to_include = $category_id ? "cat={$category_id}&" : ''; $num_posts_query = new WP_Query("{$cats_to_include}showposts={$num_posts}&offset={$post_offset}"); if ($num_posts_query->have_posts()) { ?> <div class="latest_posts"> <ul class="small-thumb"> <?php while ($num_posts_query->have_posts()) { $num_posts_query->the_post(); update_post_caches($posts); ?> <li> <?php if ($show_thumbs) { include TEMPLATEPATH . '/scripts/post-thumbnail.php'; } ?> <a class="teaser-title" title="<?php the_title(); ?> " href="<?php the_permalink(); ?> "><?php the_title(); ?> </a> <?php if ($show_date_author) { ?> <div class="date-author"><?php echo get_the_date(); ?> by <?php the_author_posts_link(); ?> </div> <?php } ?> <div class="teaser-content"><?php if ($num_words_limit) { echo custom_string_length_by_words(get_the_excerpt(), $num_words_limit) . '...'; } ?> </div> <?php if ($show_more_link) { ?> <a title="<?php the_title_attribute(); ?> " href="<?php the_permalink(); ?> " class="read-more-align-right"><span><?php esc_html_e('Read more', 'udesign'); ?> </span> →</a> <?php } ?> <div class="clear"></div> </li> <?php } ?> </ul> </div><!-- end widget_recent_posts --> <?php } wp_reset_postdata(); /* After widget (defined by themes). */ echo $after_widget; }
function &get_posts() { global $wpdb, $pagenow, $user_ID; do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; $q = $this->fill_query_vars($q); // First let's clear some variables $distinct = ''; $whichcat = ''; $whichauthor = ''; $whichpage = ''; $result = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; if (!isset($q['post_type'])) { $q['post_type'] = 'post'; } $post_type = $q['post_type']; if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } else { if ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = (int) $q['page']; $q['page'] = abs($q['page']); } $add_hours = intval(get_option('gmt_offset')); $add_minutes = intval(60 * (get_option('gmt_offset') - $add_hours)); $wp_posts_post_date_field = "post_date"; // "DATE_ADD(post_date, INTERVAL '$add_hours:$add_minutes' HOUR_MINUTE)"; // If a month is specified in the querystring, load that month if ((int) $q['m']) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= ' AND MONTH(post_date)=' . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= ' AND DAYOFMONTH(post_date)=' . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= ' AND HOUR(post_date)=' . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= ' AND MINUTE(post_date)=' . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= ' AND SECOND(post_date)=' . substr($q['m'], 12, 2); } } if ((int) $q['hour']) { $q['hour'] = '' . intval($q['hour']); $where .= " AND HOUR(post_date)='" . $q['hour'] . "'"; } if ((int) $q['minute']) { $q['minute'] = '' . intval($q['minute']); $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'"; } if ((int) $q['second']) { $q['second'] = '' . intval($q['second']); $where .= " AND SECOND(post_date)='" . $q['second'] . "'"; } if ((int) $q['year']) { $q['year'] = '' . intval($q['year']); $where .= " AND YEAR(post_date)='" . $q['year'] . "'"; } if ((int) $q['monthnum']) { $q['monthnum'] = '' . intval($q['monthnum']); $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'"; } if ((int) $q['day']) { $q['day'] = '' . intval($q['day']); $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'"; } // Compat. Map subpost to attachment. if ('' != $q['subpost']) { $q['attachment'] = $q['subpost']; } if ('' != $q['subpost_id']) { $q['attachment_id'] = $q['subpost_id']; } if ('' != $q['name']) { $q['name'] = sanitize_title($q['name']); $where .= " AND post_name = '" . $q['name'] . "'"; } else { if ('' != $q['pagename']) { $reqpage = get_page_by_path($q['pagename']); if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } if ('page' == get_option('show_on_front') && $reqpage == get_option('page_for_posts')) { $this->is_singular = false; $this->is_page = false; $this->is_home = true; $this->is_posts_page = true; } else { $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename']))); $page_paths = '/' . trim($q['pagename'], '/'); $q['pagename'] = sanitize_title(basename($page_paths)); $q['name'] = $q['pagename']; $where .= " AND (ID = '{$reqpage}')"; } } elseif ('' != $q['attachment']) { $q['attachment'] = str_replace('%2F', '/', urlencode(urldecode($q['attachment']))); $attach_paths = '/' . trim($q['attachment'], '/'); $q['attachment'] = sanitize_title(basename($attach_paths)); $q['name'] = $q['attachment']; $where .= " AND post_name = '" . $q['attachment'] . "'"; } } if ((int) $q['w']) { $q['w'] = '' . intval($q['w']); $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'"; } if (intval($q['comments_popup'])) { $q['p'] = intval($q['comments_popup']); } // If a attachment is requested by number, let it supercede any post number. if ($q['attachment_id'] != '' && intval($q['attachment_id']) != 0) { $q['p'] = (int) $q['attachment_id']; } // If a post number is specified, load that post if ($q['p'] != '' && intval($q['p']) != 0) { $q['p'] = (int) $q['p']; $where = ' AND ID = ' . $q['p']; } if ($q['page_id'] != '' && intval($q['page_id']) != 0) { $q['page_id'] = intval($q['page_id']); if ('page' == get_option('show_on_front') && $q['page_id'] == get_option('page_for_posts')) { $this->is_singular = false; $this->is_page = false; $this->is_home = true; $this->is_posts_page = true; } else { $q['p'] = $q['page_id']; $where = ' AND ID = ' . $q['page_id']; } } // If a search pattern is specified, load the posts that match if (!empty($q['s'])) { // added slashes screw with quote grouping when done early, so done later $q['s'] = stripslashes($q['s']); if ($q['sentence']) { $q['search_terms'] = array($q['s']); } else { preg_match_all('/".*?("|$)|((?<=[\\s",+])|^)[^\\s",+]+/', $q[s], $matches); $q['search_terms'] = array_map(create_function('$a', 'return trim($a, "\\"\'\\n\\r ");'), $matches[0]); } $n = $q['exact'] ? '' : '%'; $searchand = ''; foreach ((array) $q['search_terms'] as $term) { $term = addslashes_gpc($term); $search .= "{$searchand}((post_title LIKE '{$n}{$term}{$n}') OR (post_content LIKE '{$n}{$term}{$n}'))"; $searchand = ' AND '; } $term = addslashes_gpc($q['s']); if (!$q['sentence'] && count($q['search_terms']) > 1 && $q['search_terms'][0] != $q['s']) { $search .= " OR (post_title LIKE '{$n}{$term}{$n}') OR (post_content LIKE '{$n}{$term}{$n}')"; } if (!empty($search)) { $search = " AND ({$search}) "; } } // Category stuff if (empty($q['cat']) || $q['cat'] == '0' || ($this->is_single || $this->is_page)) { $whichcat = ''; } else { $q['cat'] = '' . urldecode($q['cat']) . ''; $q['cat'] = addslashes_gpc($q['cat']); $join = " LEFT JOIN {$wpdb->post2cat} ON ({$wpdb->posts}.ID = {$wpdb->post2cat}.post_id) "; $cat_array = preg_split('/[,\\s]+/', $q['cat']); $in_cats = $out_cats = $out_posts = ''; foreach ($cat_array as $cat) { $cat = intval($cat); $in = strstr($cat, '-') ? false : true; $cat = trim($cat, '-'); if ($in) { $in_cats .= "{$cat}, " . get_category_children($cat, '', ', '); } else { $out_cats .= "{$cat}, " . get_category_children($cat, '', ', '); } } $in_cats = substr($in_cats, 0, -2); $out_cats = substr($out_cats, 0, -2); if (strlen($in_cats) > 0) { $in_cats = " AND {$wpdb->post2cat}.category_id IN ({$in_cats})"; } if (strlen($out_cats) > 0) { $ids = $wpdb->get_col("SELECT post_id FROM {$wpdb->post2cat} WHERE {$wpdb->post2cat}.category_id IN ({$out_cats})"); if (is_array($ids) && count($ids > 0)) { foreach ($ids as $id) { $out_posts .= "{$id}, "; } $out_posts = substr($out_posts, 0, -2); } if (strlen($out_posts) > 0) { $out_cats = " AND {$wpdb->posts}.ID NOT IN ({$out_posts})"; } else { $out_cats = ''; } } $whichcat = $in_cats . $out_cats; $groupby = "{$wpdb->posts}.ID"; } // Category stuff for nice URLs if ('' != $q['category_name']) { $reqcat = get_category_by_path($q['category_name']); $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name']))); $cat_paths = '/' . trim($q['category_name'], '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = '/' . trim(urldecode($q['category_name']), '/'); $q['category_name'] = sanitize_title(basename($cat_paths)); $cat_paths = explode('/', $cat_paths); $cat_path = ''; foreach ((array) $cat_paths as $pathdir) { $cat_path .= ($pathdir != '' ? '/' : '') . sanitize_title($pathdir); } //if we don't match the entire hierarchy fallback on just matching the nicename if (empty($reqcat)) { $reqcat = get_category_by_path($q['category_name'], false); } if (!empty($reqcat)) { $reqcat = $reqcat->cat_ID; } else { $reqcat = 0; } $q['cat'] = $reqcat; $tables = ", {$wpdb->post2cat}, {$wpdb->categories}"; $join = " LEFT JOIN {$wpdb->post2cat} ON ({$wpdb->posts}.ID = {$wpdb->post2cat}.post_id) LEFT JOIN {$wpdb->categories} ON ({$wpdb->post2cat}.category_id = {$wpdb->categories}.cat_ID) "; $whichcat = " AND category_id IN ({$q['cat']}, "; $whichcat .= get_category_children($q['cat'], '', ', '); $whichcat = substr($whichcat, 0, -2); $whichcat .= ")"; $groupby = "{$wpdb->posts}.ID"; } // Author/user stuff if (empty($q['author']) || $q['author'] == '0') { $whichauthor = ''; } else { $q['author'] = '' . urldecode($q['author']) . ''; $q['author'] = addslashes_gpc($q['author']); if (stristr($q['author'], '-')) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = '' . intval($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\\s]+/', $q['author']); $whichauthor .= ' AND (post_author ' . $eq . ' ' . intval($author_array[0]); for ($i = 1; $i < count($author_array); $i = $i + 1) { $whichauthor .= ' ' . $andor . ' post_author ' . $eq . ' ' . intval($author_array[$i]); } $whichauthor .= ')'; } // Author stuff for nice URLs if ('' != $q['author_name']) { if (stristr($q['author_name'], '/')) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; #no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; #there was a trailling slash } } $q['author_name'] = sanitize_title($q['author_name']); $q['author'] = $wpdb->get_var("SELECT ID FROM {$wpdb->users} WHERE user_nicename='" . $q['author_name'] . "'"); $whichauthor .= ' AND (post_author = ' . intval($q['author']) . ')'; } $where .= $search . $whichcat . $whichauthor; if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') { $q['order'] = 'DESC'; } // Order by if (empty($q['orderby'])) { $q['orderby'] = 'post_date ' . $q['order']; } else { // Used to filter values $allowed_keys = array('author', 'date', 'category', 'title', 'modified', 'menu_order'); $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = explode(' ', $q['orderby']); if (empty($orderby_array)) { $orderby_array[] = $q['orderby']; } $q['orderby'] = ''; for ($i = 0; $i < count($orderby_array); $i++) { // Only allow certain values for safety $orderby = $orderby_array[$i]; if ('menu_order' != $orderby) { $orderby = 'post_' . $orderby; } if (in_array($orderby_array[$i], $allowed_keys)) { $q['orderby'] .= ($i == 0 ? '' : ',') . "{$orderby} {$q['order']}"; } } if (empty($q['orderby'])) { $q['orderby'] = 'post_date ' . $q['order']; } } if ($this->is_attachment) { $where .= " AND (post_type = 'attachment')"; } elseif ($this->is_page) { $where .= " AND (post_type = 'page')"; } elseif ($this->is_single) { $where .= " AND (post_type = 'post')"; } else { $where .= " AND (post_type = '{$post_type}' AND (post_status = 'publish'"; if (is_admin()) { $where .= " OR post_status = 'future' OR post_status = 'draft'"; } if (is_user_logged_in()) { if ('post' == $post_type) { $cap = 'read_private_posts'; } else { $cap = 'read_private_pages'; } if (current_user_can($cap)) { $where .= " OR post_status = 'private'"; } else { $where .= " OR post_author = {$user_ID} AND post_status = 'private'"; } } $where .= '))'; } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. $where = apply_filters('posts_where', $where); $join = apply_filters('posts_join', $join); // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = abs(intval($q['paged'])); if (empty($page)) { $page = 1; } if (empty($q['offset'])) { $pgstrt = ''; $pgstrt = (intval($page) - 1) * $q['posts_per_page'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } else { // we're ignoring $page and using 'offset' $q['offset'] = abs(intval($q['offset'])); $pgstrt = $q['offset'] . ', '; $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } } // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. $where = apply_filters('posts_where_paged', $where); $groupby = apply_filters('posts_groupby', $groupby); if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } $join = apply_filters('posts_join_paged', $join); $orderby = apply_filters('posts_orderby', $q['orderby']); $distinct = apply_filters('posts_distinct', $distinct); $fields = apply_filters('posts_fields', "{$wpdb->posts}.*"); $limits = apply_filters('post_limits', $limits); $found_rows = ''; if (!empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $request = " SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} ORDER BY {$orderby} {$limits}"; $this->request = apply_filters('posts_request', $request); $this->posts = $wpdb->get_results($this->request); if (!empty($limits)) { $found_posts_query = apply_filters('found_posts_query', 'SELECT FOUND_ROWS()'); $this->found_posts = $wpdb->get_var($found_posts_query); $this->found_posts = apply_filters('found_posts', $this->found_posts); $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); //$type = get_post_type($this->posts[0]); if ('publish' != $status) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ('draft' == $status) { // User must have edit permissions on the draft to preview. if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; $this->posts[0]->post_date = current_time('mysql'); } } else { if ('future' == $status) { $this->is_preview = true; if (!current_user_can('edit_post', $this->posts[0]->ID)) { $this->posts = array(); } } else { if (!current_user_can('read_post', $this->posts[0]->ID)) { $this->posts = array(); } } } } } } $this->posts = apply_filters('the_posts', $this->posts); update_post_caches($this->posts); $this->post_count = count($this->posts); if ($this->post_count > 0) { $this->post = $this->posts[0]; } return $this->posts; }
/** * Function called when query parameters are processed by Wordpress. * * @param $query query parameters * @return array() $query processed * * @since 1.0 */ function filter_request($query) { global $q_config, $wp_query, $wp; if (isset($wp->matched_query)) { $query = wp_parse_args($wp->matched_query); } foreach (get_post_types() as $post_type) { if (array_key_exists($post_type, $query) && !in_array($post_type, array('post', 'page'))) { $query['post_type'] = $post_type; } } $page_foundit = false; // -> page if (isset($query['pagename']) || isset($query['page_id'])) { $page = wp_cache_get('qts_page_request'); if (!$page) { $page = isset($query['page_id']) ? get_page($query['page_id']) : $this->get_page_by_path($query['pagename']); } if (!$page) { return $query; } $id = $page->ID; $cache_array = array($page); update_post_caches($cache_array, 'page'); // caching query :) wp_cache_delete('qts_page_request'); $query['pagename'] = get_page_uri($page); $function = 'get_page_link'; // -> custom post type } elseif (isset($query['post_type'])) { $page_slug = isset($query['name']) && !empty($query['name']) ? $query['name'] : $query[$query['post_type']]; $page = $this->get_page_by_path($page_slug, OBJECT, $query['post_type']); if (!$page) { return $query; } $id = $page->ID; $cache_array = array($page); update_post_caches($cache_array, $query['post_type']); // caching query :) $query['name'] = $query[$query['post_type']] = get_page_uri($page); $function = 'get_post_permalink'; // -> post } elseif (isset($query['name']) || isset($query['p'])) { $post = isset($query['p']) ? get_post($query['p']) : $this->get_page_by_path($query['name'], OBJECT, 'post'); if (!$post) { return $query; } $query['name'] = $post->post_name; $id = $post->ID; $cache_array = array($post); update_post_caches($cache_array); $function = 'get_permalink'; // -> category } elseif (isset($query['category_name']) || isset($query['cat'])) { if (isset($query['category_name'])) { $term_slug = $this->get_last_slash($query['category_name']); } $term = isset($query['cat']) ? get_term($query['cat'], 'category') : $this->get_term_by('slug', $term_slug, 'category'); if (!$term) { return $query; } $cache_array = array($term); update_term_cache($cache_array, 'category'); // caching query :) $id = $term->term_id; $query['category_name'] = $term->slug; // uri $function = 'get_category_link'; // -> tag } elseif (isset($query['tag'])) { $term = $this->get_term_by('slug', $query['tag'], 'post_tag'); if (!$term) { return $query; } $cache_array = array($term); update_term_cache($cache_array, 'post_tag'); // caching query :) $id = $term->term_id; $query['tag'] = $term->slug; $function = 'get_tag_link'; } // -> taxonomy $taxonomies = get_taxonomies(array('public' => true, '_builtin' => false)); foreach ($taxonomies as $term_name) { if (isset($query[$term_name])) { $term_slug = $this->get_last_slash($query[$term_name]); $term = $this->get_term_by('slug', $term_slug, $term_name); if (!$term) { return $query; } $cache_array = array($term); update_term_cache($cache_array, $term_name); // caching query :) $id = $term; $query[$term_name] = $term->slug; $function = 'get_term_link'; } } // -> home url if (empty($query)) { $function = 'home_url'; $id = ''; } if (isset($function)) { // parse all languages links foreach ($q_config['enabled_languages'] as $lang) { $this->lang = $lang; $this->current_url[$lang] = apply_filters('qts_url_args', call_user_func($function, $id)); } $this->lang = false; } return $query; }
function cp_collect_featured_images() { global $wpdb, $posts, $pageposts, $wp_query, $images_data; if (isset($posts) && is_array($posts)) { foreach ($posts as $post) { $post_ids[] = $post->ID; } } if (isset($pageposts) && is_array($pageposts)) { foreach ($pageposts as $post) { $post_ids[] = $post->ID; } } if (isset($wp_query->posts) && is_array($wp_query->posts)) { foreach ($wp_query->posts as $post) { $post_ids[] = $post->ID; } } if (isset($post_ids) && is_array($post_ids)) { $post_ids = array_unique($post_ids); $post_list = implode(",", $post_ids); $images = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE post_parent IN ({$post_list}) AND (post_mime_type LIKE 'image/%') AND post_type = 'attachment' AND (post_status = 'inherit') ORDER BY ID ASC"); } if (isset($images) && is_array($images)) { foreach ($images as $image) { if (!isset($images_data[$image->post_parent])) { $images_data[$image->post_parent] = $image->ID; } } // create cache for images update_post_caches($images, 'post', false, true); } if (isset($post_ids) && is_array($post_ids)) { foreach ($post_ids as $post_id) { if (!isset($images_data[$post_id])) { $images_data[$post_id] = 0; } } } }
/** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * * @return array List of posts. */ public function get_posts() { $this->parse_query(); /** * Fires after the query variable object is created, but before the actual query is run. * * Note: If using conditional tags, use the method versions within the passed instance * (e.g. $this->is_main_query() instead of is_main_query()). This is because the functions * like is_main_query() test against the global $wp_query instance, not the passed one. * * @since 2.0.0 * * @param WP_Query &$this The WP_Query instance (passed by reference). */ do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q =& $this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars($q); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5(serialize($this->query_vars)); if ($hash != $this->query_vars_hash) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $post_status_join = false; $page = 1; if (isset($q['caller_get_posts'])) { _deprecated_argument('WP_Query', '3.1.0', __('"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.')); if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = $q['caller_get_posts']; } } if (!isset($q['ignore_sticky_posts'])) { $q['ignore_sticky_posts'] = false; } if (!isset($q['suppress_filters'])) { $q['suppress_filters'] = false; } if (!isset($q['cache_results'])) { if (wp_using_ext_object_cache()) { $q['cache_results'] = false; } else { $q['cache_results'] = true; } } if (!isset($q['update_post_term_cache'])) { $q['update_post_term_cache'] = true; } if (!isset($q['lazy_load_term_meta'])) { $q['lazy_load_term_meta'] = $q['update_post_term_cache']; } if (!isset($q['update_post_meta_cache'])) { $q['update_post_meta_cache'] = true; } if (!isset($q['post_type'])) { if ($this->is_search) { $q['post_type'] = 'any'; } else { $q['post_type'] = ''; } } $post_type = $q['post_type']; if (empty($q['posts_per_page'])) { $q['posts_per_page'] = get_option('posts_per_page'); } if (isset($q['showposts']) && $q['showposts']) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) { $q['posts_per_page'] = $q['posts_per_archive_page']; } if (!isset($q['nopaging'])) { if ($q['posts_per_page'] == -1) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ($this->is_feed) { // This overrides posts_per_page. if (!empty($q['posts_per_rss'])) { $q['posts_per_page'] = $q['posts_per_rss']; } else { $q['posts_per_page'] = get_option('posts_per_rss'); } $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ($q['posts_per_page'] < -1) { $q['posts_per_page'] = abs($q['posts_per_page']); } elseif ($q['posts_per_page'] == 0) { $q['posts_per_page'] = 1; } if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) { $q['comments_per_page'] = get_option('comments_per_page'); } if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if (isset($q['page'])) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present. if (isset($q['no_found_rows'])) { $q['no_found_rows'] = (bool) $q['no_found_rows']; } else { $q['no_found_rows'] = false; } switch ($q['fields']) { case 'ids': $fields = "{$this->db->posts}.ID"; break; case 'id=>parent': $fields = "{$this->db->posts}.ID, {$this->db->posts}.post_parent"; break; default: $fields = "{$this->db->posts}.*"; } if ('' !== $q['menu_order']) { $where .= " AND {$this->db->posts}.menu_order = " . $q['menu_order']; } // The "m" parameter is meant for months but accepts datetimes of varying specificity if ($q['m']) { $where .= " AND YEAR({$this->db->posts}.post_date)=" . substr($q['m'], 0, 4); if (strlen($q['m']) > 5) { $where .= " AND MONTH({$this->db->posts}.post_date)=" . substr($q['m'], 4, 2); } if (strlen($q['m']) > 7) { $where .= " AND DAYOFMONTH({$this->db->posts}.post_date)=" . substr($q['m'], 6, 2); } if (strlen($q['m']) > 9) { $where .= " AND HOUR({$this->db->posts}.post_date)=" . substr($q['m'], 8, 2); } if (strlen($q['m']) > 11) { $where .= " AND MINUTE({$this->db->posts}.post_date)=" . substr($q['m'], 10, 2); } if (strlen($q['m']) > 13) { $where .= " AND SECOND({$this->db->posts}.post_date)=" . substr($q['m'], 12, 2); } } // Handle the other individual date parameters $date_parameters = array(); if ('' !== $q['hour']) { $date_parameters['hour'] = $q['hour']; } if ('' !== $q['minute']) { $date_parameters['minute'] = $q['minute']; } if ('' !== $q['second']) { $date_parameters['second'] = $q['second']; } if ($q['year']) { $date_parameters['year'] = $q['year']; } if ($q['monthnum']) { $date_parameters['monthnum'] = $q['monthnum']; } if ($q['w']) { $date_parameters['week'] = $q['w']; } if ($q['day']) { $date_parameters['day'] = $q['day']; } if ($date_parameters) { $date_query = new WP_Date_Query(array($date_parameters)); $where .= $date_query->get_sql(); } unset($date_parameters, $date_query); // Handle complex date queries if (!empty($q['date_query'])) { $this->date_query = new WP_Date_Query($q['date_query']); $where .= $this->date_query->get_sql(); } // If we've got a post_type AND it's not "any" post_type. if (!empty($q['post_type']) && 'any' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) { continue; } if (!$ptype_obj->hierarchical) { // Non-hierarchical post types can directly use 'name'. $q['name'] = $q[$ptype_obj->query_var]; } else { // Hierarchical post types will operate through 'pagename'. $q['pagename'] = $q[$ptype_obj->query_var]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ('' !== $q['title']) { $where .= $this->db->prepare(" AND {$this->db->posts}.post_title = %s", stripslashes($q['title'])); } // Parameters related to 'post_name'. if ('' != $q['name']) { $q['name'] = sanitize_title_for_query($q['name']); $where .= " AND {$this->db->posts}.post_name = '" . $q['name'] . "'"; } elseif ('' != $q['pagename']) { if (isset($this->queried_object_id)) { $reqpage = $this->queried_object_id; } else { if ('page' != $q['post_type']) { foreach ((array) $q['post_type'] as $_post_type) { $ptype_obj = get_post_type_object($_post_type); if (!$ptype_obj || !$ptype_obj->hierarchical) { continue; } $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ($reqpage) { break; } } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if (!empty($reqpage)) { $reqpage = $reqpage->ID; } else { $reqpage = 0; } } $page_for_posts = get_option('page_for_posts'); if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) { $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename'])); $q['name'] = $q['pagename']; $where .= " AND ({$this->db->posts}.ID = '{$reqpage}')"; $reqpage_obj = get_post($reqpage); if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ('' != $q['attachment']) { $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment'])); $q['name'] = $q['attachment']; $where .= " AND {$this->db->posts}.post_name = '" . $q['attachment'] . "'"; } elseif (is_array($q['post_name__in']) && !empty($q['post_name__in'])) { $q['post_name__in'] = array_map('sanitize_title_for_query', $q['post_name__in']); $post_name__in = "'" . implode("','", $q['post_name__in']) . "'"; $where .= " AND {$this->db->posts}.post_name IN ({$post_name__in})"; } // If an attachment is requested by number, let it supersede any post number. if ($q['attachment_id']) { $q['p'] = absint($q['attachment_id']); } // If a post number is specified, load that post if ($q['p']) { $where .= " AND {$this->db->posts}.ID = " . $q['p']; } elseif ($q['post__in']) { $post__in = implode(',', array_map('absint', $q['post__in'])); $where .= " AND {$this->db->posts}.ID IN ({$post__in})"; } elseif ($q['post__not_in']) { $post__not_in = implode(',', array_map('absint', $q['post__not_in'])); $where .= " AND {$this->db->posts}.ID NOT IN ({$post__not_in})"; } if (is_numeric($q['post_parent'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.post_parent = %d ", $q['post_parent']); } elseif ($q['post_parent__in']) { $post_parent__in = implode(',', array_map('absint', $q['post_parent__in'])); $where .= " AND {$this->db->posts}.post_parent IN ({$post_parent__in})"; } elseif ($q['post_parent__not_in']) { $post_parent__not_in = implode(',', array_map('absint', $q['post_parent__not_in'])); $where .= " AND {$this->db->posts}.post_parent NOT IN ({$post_parent__not_in})"; } if ($q['page_id']) { if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) { $q['p'] = $q['page_id']; $where = " AND {$this->db->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match. if (strlen($q['s'])) { $search = $this->parse_search($q); } if (!$q['suppress_filters']) { /** * Filters the search SQL that is used in the WHERE clause of WP_Query. * * @since 3.0.0 * * @param string $search Search SQL for WHERE clause. * @param WP_Query $this The current WP_Query object. */ $search = apply_filters_ref_array('posts_search', array($search, &$this)); } // Taxonomies if (!$this->is_singular) { $this->parse_tax_query($q); $clauses = $this->tax_query->get_sql($this->db->posts, 'ID'); $join .= $clauses['join']; $where .= $clauses['where']; } if ($this->is_tax) { if (empty($post_type)) { // Do a fully inclusive search for currently registered post types of queried taxonomies $post_type = array(); $taxonomies = array_keys($this->tax_query->queried_terms); foreach (get_post_types(array('exclude_from_search' => false)) as $pt) { $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies($pt); if (array_intersect($taxonomies, $object_taxonomies)) { $post_type[] = $pt; } } if (!$post_type) { $post_type = 'any'; } elseif (count($post_type) == 1) { $post_type = $post_type[0]; } $post_status_join = true; } elseif (in_array('attachment', (array) $post_type)) { $post_status_join = true; } } /* * Ensure that 'taxonomy', 'term', 'term_id', 'cat', and * 'category_name' vars are set for backward compatibility. */ if (!empty($this->tax_query->queried_terms)) { /* * Set 'taxonomy', 'term', and 'term_id' to the * first taxonomy other than 'post_tag' or 'category'. */ if (!isset($q['taxonomy'])) { foreach ($this->tax_query->queried_terms as $queried_taxonomy => $queried_items) { if (empty($queried_items['terms'][0])) { continue; } if (!in_array($queried_taxonomy, array('category', 'post_tag'))) { $q['taxonomy'] = $queried_taxonomy; if ('slug' === $queried_items['field']) { $q['term'] = $queried_items['terms'][0]; } else { $q['term_id'] = $queried_items['terms'][0]; } // Take the first one we find. break; } } } // 'cat', 'category_name', 'tag_id' foreach ($this->tax_query->queried_terms as $queried_taxonomy => $queried_items) { if (empty($queried_items['terms'][0])) { continue; } if ('category' === $queried_taxonomy) { $the_cat = get_term_by($queried_items['field'], $queried_items['terms'][0], 'category'); if ($the_cat) { $this->set('cat', $the_cat->term_id); $this->set('category_name', $the_cat->slug); } unset($the_cat); } if ('post_tag' === $queried_taxonomy) { $the_tag = get_term_by($queried_items['field'], $queried_items['terms'][0], 'post_tag'); if ($the_tag) { $this->set('tag_id', $the_tag->term_id); } unset($the_tag); } } } if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) { $groupby = "{$this->db->posts}.ID"; } // Author/user stuff if (!empty($q['author']) && $q['author'] != '0') { $q['author'] = addslashes_gpc('' . urldecode($q['author'])); $authors = array_unique(array_map('intval', preg_split('/[,\\s]+/', $q['author']))); foreach ($authors as $author) { $key = $author > 0 ? 'author__in' : 'author__not_in'; $q[$key][] = abs($author); } $q['author'] = implode(',', $authors); } if (!empty($q['author__not_in'])) { $author__not_in = implode(',', array_map('absint', array_unique((array) $q['author__not_in']))); $where .= " AND {$this->db->posts}.post_author NOT IN ({$author__not_in}) "; } elseif (!empty($q['author__in'])) { $author__in = implode(',', array_map('absint', array_unique((array) $q['author__in']))); $where .= " AND {$this->db->posts}.post_author IN ({$author__in}) "; } // Author stuff for nice URLs if ('' != $q['author_name']) { if (strpos($q['author_name'], '/') !== false) { $q['author_name'] = explode('/', $q['author_name']); if ($q['author_name'][count($q['author_name']) - 1]) { $q['author_name'] = $q['author_name'][count($q['author_name']) - 1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name']) - 2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query($q['author_name']); $q['author'] = get_user_by('slug', $q['author_name']); if ($q['author']) { $q['author'] = $q['author']->ID; } $whichauthor .= " AND ({$this->db->posts}.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) { $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $this->db->posts); } $where .= $search . $whichauthor . $whichmimetype; if (!empty($this->meta_query->queries)) { $clauses = $this->meta_query->get_sql('post', $this->db->posts, 'ID', $this); $join .= $clauses['join']; $where .= $clauses['where']; } $rand = isset($q['orderby']) && 'rand' === $q['orderby']; if (!isset($q['order'])) { $q['order'] = $rand ? '' : 'DESC'; } else { $q['order'] = $rand ? '' : $this->parse_order($q['order']); } // Order by. if (empty($q['orderby'])) { /* * Boolean false or empty array blanks out ORDER BY, * while leaving the value unset or otherwise empty sets the default. */ if (isset($q['orderby']) && (is_array($q['orderby']) || false === $q['orderby'])) { $orderby = ''; } else { $orderby = "{$this->db->posts}.post_date " . $q['order']; } } elseif ('none' == $q['orderby']) { $orderby = ''; } elseif ($q['orderby'] == 'post__in' && !empty($post__in)) { $orderby = "FIELD( {$this->db->posts}.ID, {$post__in} )"; } elseif ($q['orderby'] == 'post_parent__in' && !empty($post_parent__in)) { $orderby = "FIELD( {$this->db->posts}.post_parent, {$post_parent__in} )"; } elseif ($q['orderby'] == 'post_name__in' && !empty($post_name__in)) { $orderby = "FIELD( {$this->db->posts}.post_name, {$post_name__in} )"; } else { $orderby_array = array(); if (is_array($q['orderby'])) { foreach ($q['orderby'] as $_orderby => $order) { $orderby = addslashes_gpc(urldecode($_orderby)); $parsed = $this->parse_orderby($orderby); if (!$parsed) { continue; } $orderby_array[] = $parsed . ' ' . $this->parse_order($order); } $orderby = implode(', ', $orderby_array); } else { $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); foreach (explode(' ', $q['orderby']) as $i => $orderby) { $parsed = $this->parse_orderby($orderby); // Only allow certain values for safety. if (!$parsed) { continue; } $orderby_array[] = $parsed; } $orderby = implode(' ' . $q['order'] . ', ', $orderby_array); if (empty($orderby)) { $orderby = "{$this->db->posts}.post_date " . $q['order']; } elseif (!empty($q['order'])) { $orderby .= " {$q['order']}"; } } } // Order search results by relevance only when another "orderby" is not specified in the query. if (!empty($q['s'])) { $search_orderby = ''; if (!empty($q['search_orderby_title']) && (empty($q['orderby']) && !$this->is_feed) || isset($q['orderby']) && 'relevance' === $q['orderby']) { $search_orderby = $this->parse_search_order($q); } if (!$q['suppress_filters']) { /** * Filters the ORDER BY used when ordering search results. * * @since 3.7.0 * * @param string $search_orderby The ORDER BY clause. * @param WP_Query $this The current WP_Query instance. */ $search_orderby = apply_filters('posts_search_orderby', $search_orderby, $this); } if ($search_orderby) { $orderby = $orderby ? $search_orderby . ', ' . $orderby : $search_orderby; } } if (is_array($post_type) && count($post_type) > 1) { $post_type_cap = 'multiple_post_type'; } else { if (is_array($post_type)) { $post_type = reset($post_type); } $post_type_object = get_post_type_object($post_type); if (empty($post_type_object)) { $post_type_cap = $post_type; } } if (isset($q['post_password'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.post_password = %s", $q['post_password']); if (empty($q['perm'])) { $q['perm'] = 'readable'; } } elseif (isset($q['has_password'])) { $where .= sprintf(" AND {$this->db->posts}.post_password %s ''", $q['has_password'] ? '!=' : '='); } if (!empty($q['comment_status'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.comment_status = %s ", $q['comment_status']); } if (!empty($q['ping_status'])) { $where .= $this->db->prepare(" AND {$this->db->posts}.ping_status = %s ", $q['ping_status']); } if ('any' == $post_type) { $in_search_post_types = get_post_types(array('exclude_from_search' => false)); if (empty($in_search_post_types)) { $where .= ' AND 1=0 '; } else { $where .= " AND {$this->db->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')"; } } elseif (!empty($post_type) && is_array($post_type)) { $where .= " AND {$this->db->posts}.post_type IN ('" . join("', '", $post_type) . "')"; } elseif (!empty($post_type)) { $where .= " AND {$this->db->posts}.post_type = '{$post_type}'"; $post_type_object = get_post_type_object($post_type); } elseif ($this->is_attachment) { $where .= " AND {$this->db->posts}.post_type = 'attachment'"; $post_type_object = get_post_type_object('attachment'); } elseif ($this->is_page) { $where .= " AND {$this->db->posts}.post_type = 'page'"; $post_type_object = get_post_type_object('page'); } else { $where .= " AND {$this->db->posts}.post_type = 'post'"; $post_type_object = get_post_type_object('post'); } $edit_cap = 'edit_post'; $read_cap = 'read_post'; if (!empty($post_type_object)) { $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } $user_id = get_current_user_id(); $q_status = array(); if (!empty($q['post_status'])) { $statuswheres = array(); $q_status = $q['post_status']; if (!is_array($q_status)) { $q_status = explode(',', $q_status); } $r_status = array(); $p_status = array(); $e_status = array(); if (in_array('any', $q_status)) { foreach (get_post_stati(array('exclude_from_search' => true)) as $status) { if (!in_array($status, $q_status)) { $e_status[] = "{$this->db->posts}.post_status <> '{$status}'"; } } } else { foreach (get_post_stati() as $status) { if (in_array($status, $q_status)) { if ('private' == $status) { $p_status[] = "{$this->db->posts}.post_status = '{$status}'"; } else { $r_status[] = "{$this->db->posts}.post_status = '{$status}'"; } } } } if (empty($q['perm']) || 'readable' != $q['perm']) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if (!empty($e_status)) { $statuswheres[] = "(" . join(' AND ', $e_status) . ")"; } if (!empty($r_status)) { if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) { $statuswheres[] = "({$this->db->posts}.post_author = {$user_id} " . "AND (" . join(' OR ', $r_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $r_status) . ")"; } } if (!empty($p_status)) { if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) { $statuswheres[] = "({$this->db->posts}.post_author = {$user_id} " . "AND (" . join(' OR ', $p_status) . "))"; } else { $statuswheres[] = "(" . join(' OR ', $p_status) . ")"; } } if ($post_status_join) { $join .= " LEFT JOIN {$this->db->posts} AS p2 ON ({$this->db->posts}.post_parent = p2.ID) "; foreach ($statuswheres as $index => $statuswhere) { $statuswheres[$index] = "({$statuswhere} OR ({$this->db->posts}.post_status = 'inherit' AND " . str_replace($this->db->posts, 'p2', $statuswhere) . "))"; } } $where_status = implode(' OR ', $statuswheres); if (!empty($where_status)) { $where .= " AND ({$where_status})"; } } elseif (!$this->is_singular) { $where .= " AND ({$this->db->posts}.post_status = 'publish'"; // Add public states. $public_states = get_post_stati(array('public' => true)); foreach ((array) $public_states as $state) { if ('publish' == $state) { // Publish is hard-coded above. continue; } $where .= " OR {$this->db->posts}.post_status = '{$state}'"; } if ($this->is_admin) { // Add protected states that should show in the admin all list. $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true)); foreach ((array) $admin_all_states as $state) { $where .= " OR {$this->db->posts}.post_status = '{$state}'"; } } if (is_user_logged_in()) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati(array('private' => true)); foreach ((array) $private_states as $state) { $where .= current_user_can($read_private_cap) ? " OR {$this->db->posts}.post_status = '{$state}'" : " OR {$this->db->posts}.post_author = {$user_id} AND {$this->db->posts}.post_status = '{$state}'"; } } $where .= ')'; } /* * Apply filters on where and join prior to paging so that any * manipulations to them are reflected in the paging by day queries. */ if (!$q['suppress_filters']) { /** * Filters the WHERE clause of the query. * * @since 1.5.0 * * @param string $where The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $where = apply_filters_ref_array('posts_where', array($where, &$this)); /** * Filters the JOIN clause of the query. * * @since 1.5.0 * * @param string $where The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $join = apply_filters_ref_array('posts_join', array($join, &$this)); } // Paging if (empty($q['nopaging']) && !$this->is_singular) { $page = absint($q['paged']); if (!$page) { $page = 1; } // If 'offset' is provided, it takes precedence over 'paged'. if (isset($q['offset']) && is_numeric($q['offset'])) { $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; } else { $pgstrt = absint(($page - 1) * $q['posts_per_page']) . ', '; } $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } // Comments feeds if ($this->is_comment_feed && !$this->is_singular) { if ($this->is_archive || $this->is_search) { $cjoin = "JOIN {$this->db->posts} ON ({$this->db->comments}.comment_post_ID = {$this->db->posts}.ID) {$join} "; $cwhere = "WHERE comment_approved = '1' {$where}"; $cgroupby = "{$this->db->comments}.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN {$this->db->posts} ON ( {$this->db->comments}.comment_post_ID = {$this->db->posts}.ID )"; $cwhere = "WHERE ( post_status = 'publish' OR ( post_status = 'inherit' && post_type = 'attachment' ) ) AND comment_approved = '1'"; $cgroupby = ''; } if (!$q['suppress_filters']) { /** * Filters the JOIN clause of the comments feed query before sending. * * @since 2.2.0 * * @param string $cjoin The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this)); /** * Filters the WHERE clause of the comments feed query before sending. * * @since 2.2.0 * * @param string $cwhere The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this)); /** * Filters the GROUP BY clause of the comments feed query before sending. * * @since 2.2.0 * * @param string $cgroupby The GROUP BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this)); /** * Filters the ORDER BY clause of the comments feed query before sending. * * @since 2.8.0 * * @param string $corderby The ORDER BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); /** * Filters the LIMIT clause of the comments feed query before sending. * * @since 2.8.0 * * @param string $climits The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); } $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; $comments = (array) $this->db->get_results("SELECT {$distinct} {$this->db->comments}.* FROM {$this->db->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"); // Convert to WP_Comment $this->comments = array_map('get_comment', $comments); $this->comment_count = count($this->comments); $post_ids = array(); foreach ($this->comments as $comment) { $post_ids[] = (int) $comment->comment_post_ID; } $post_ids = join(',', $post_ids); $join = ''; if ($post_ids) { $where = "AND {$this->db->posts}.ID IN ({$post_ids}) "; } else { $where = "AND 0"; } } $pieces = array('where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits'); /* * Apply post-paging filters on where and join. Only plugins that * manipulate paging queries should use these hooks. */ if (!$q['suppress_filters']) { /** * Filters the WHERE clause of the query. * * Specifically for manipulating paging queries. * * @since 1.5.0 * * @param string $where The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $where = apply_filters_ref_array('posts_where_paged', array($where, &$this)); /** * Filters the GROUP BY clause of the query. * * @since 2.0.0 * * @param string $groupby The GROUP BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this)); /** * Filters the JOIN clause of the query. * * Specifically for manipulating paging queries. * * @since 1.5.0 * * @param string $join The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $join = apply_filters_ref_array('posts_join_paged', array($join, &$this)); /** * Filters the ORDER BY clause of the query. * * @since 1.5.1 * * @param string $orderby The ORDER BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this)); /** * Filters the DISTINCT clause of the query. * * @since 2.1.0 * * @param string $distinct The DISTINCT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this)); /** * Filters the LIMIT clause of the query. * * @since 2.1.0 * * @param string $limits The LIMIT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $limits = apply_filters_ref_array('post_limits', array($limits, &$this)); /** * Filters the SELECT clause of the query. * * @since 2.1.0 * * @param string $fields The SELECT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $fields = apply_filters_ref_array('posts_fields', array($fields, &$this)); /** * Filters all query clauses at once, for convenience. * * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, * fields (SELECT), and LIMITS clauses. * * @since 3.1.0 * * @param array $clauses The list of clauses for the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $clauses = (array) apply_filters_ref_array('posts_clauses', array(compact($pieces), &$this)); $where = isset($clauses['where']) ? $clauses['where'] : ''; $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : ''; $join = isset($clauses['join']) ? $clauses['join'] : ''; $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : ''; $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : ''; $fields = isset($clauses['fields']) ? $clauses['fields'] : ''; $limits = isset($clauses['limits']) ? $clauses['limits'] : ''; } /** * Fires to announce the query's current selection parameters. * * For use by caching plugins. * * @since 2.3.0 * * @param string $selection The assembled selection query. */ do_action('posts_selection', $where . $groupby . $orderby . $limits . $join); /* * Filters again for the benefit of caching plugins. * Regular plugins should use the hooks above. */ if (!$q['suppress_filters']) { /** * Filters the WHERE clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $where The WHERE clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $where = apply_filters_ref_array('posts_where_request', array($where, &$this)); /** * Filters the GROUP BY clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $groupby The GROUP BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this)); /** * Filters the JOIN clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $join The JOIN clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $join = apply_filters_ref_array('posts_join_request', array($join, &$this)); /** * Filters the ORDER BY clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $orderby The ORDER BY clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this)); /** * Filters the DISTINCT clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $distinct The DISTINCT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this)); /** * Filters the SELECT clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $fields The SELECT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this)); /** * Filters the LIMIT clause of the query. * * For use by caching plugins. * * @since 2.5.0 * * @param string $limits The LIMIT clause of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this)); /** * Filters all query clauses at once, for convenience. * * For use by caching plugins. * * Covers the WHERE, GROUP BY, JOIN, ORDER BY, DISTINCT, * fields (SELECT), and LIMITS clauses. * * @since 3.1.0 * * @param array $pieces The pieces of the query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $clauses = (array) apply_filters_ref_array('posts_clauses_request', array(compact($pieces), &$this)); $where = isset($clauses['where']) ? $clauses['where'] : ''; $groupby = isset($clauses['groupby']) ? $clauses['groupby'] : ''; $join = isset($clauses['join']) ? $clauses['join'] : ''; $orderby = isset($clauses['orderby']) ? $clauses['orderby'] : ''; $distinct = isset($clauses['distinct']) ? $clauses['distinct'] : ''; $fields = isset($clauses['fields']) ? $clauses['fields'] : ''; $limits = isset($clauses['limits']) ? $clauses['limits'] : ''; } if (!empty($groupby)) { $groupby = 'GROUP BY ' . $groupby; } if (!empty($orderby)) { $orderby = 'ORDER BY ' . $orderby; } $found_rows = ''; if (!$q['no_found_rows'] && !empty($limits)) { $found_rows = 'SQL_CALC_FOUND_ROWS'; } $this->request = $old_request = "SELECT {$found_rows} {$distinct} {$fields} FROM {$this->db->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; if (!$q['suppress_filters']) { /** * Filters the completed SQL query before sending. * * @since 2.0.0 * * @param string $request The complete SQL query. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this)); } /** * Filters the posts array before the query takes place. * * Return a non-null value to bypass WordPress's default post queries. * * Filtering functions that require pagination information are encouraged to set * the `found_posts` and `max_num_pages` properties of the WP_Query object, * passed to the filter by reference. If WP_Query does not perform a database * query, it will not have enough information to generate these values itself. * * @since 4.6.0 * * @param array|null $posts Return an array of post data to short-circuit WP's query, * or null to allow WP to run its normal queries. * @param WP_Query $this The WP_Query instance, passed by reference. */ $this->posts = apply_filters_ref_array('posts_pre_query', array(null, &$this)); if ('ids' == $q['fields']) { if (null === $this->posts) { $this->posts = $this->db->get_col($this->request); } $this->posts = array_map('intval', $this->posts); $this->post_count = count($this->posts); $this->set_found_posts($q, $limits); return $this->posts; } if ('id=>parent' == $q['fields']) { if (null === $this->posts) { $this->posts = $this->db->get_results($this->request); } $this->post_count = count($this->posts); $this->set_found_posts($q, $limits); $r = array(); foreach ($this->posts as $key => $post) { $this->posts[$key]->ID = (int) $post->ID; $this->posts[$key]->post_parent = (int) $post->post_parent; $r[(int) $post->ID] = (int) $post->post_parent; } return $r; } if (null === $this->posts) { $split_the_query = $old_request == $this->request && "{$this->db->posts}.*" == $fields && !empty($limits) && $q['posts_per_page'] < 500; /** * Filters whether to split the query. * * Splitting the query will cause it to fetch just the IDs of the found posts * (and then individually fetch each post by ID), rather than fetching every * complete row at once. One massive result vs. many small results. * * @since 3.4.0 * * @param bool $split_the_query Whether or not to split the query. * @param WP_Query $this The WP_Query instance. */ $split_the_query = apply_filters('split_the_query', $split_the_query, $this); if ($split_the_query) { // First get the IDs and then fill in the objects $this->request = "SELECT {$found_rows} {$distinct} {$this->db->posts}.ID FROM {$this->db->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}"; /** * Filters the Post IDs SQL request before sending. * * @since 3.4.0 * * @param string $request The post ID request. * @param WP_Query $this The WP_Query instance. */ $this->request = apply_filters('posts_request_ids', $this->request, $this); $ids = $this->db->get_col($this->request); if ($ids) { $this->posts = $ids; $this->set_found_posts($q, $limits); _prime_post_caches($ids, $q['update_post_term_cache'], $q['update_post_meta_cache']); } else { $this->posts = array(); } } else { $this->posts = $this->db->get_results($this->request); $this->set_found_posts($q, $limits); } } // Convert to WP_Post objects. if ($this->posts) { $this->posts = array_map('get_post', $this->posts); } if (!$q['suppress_filters']) { /** * Filters the raw post results array, prior to status checks. * * @since 2.3.0 * * @param array $posts The post results array. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this)); } if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) { /** This filter is documented in wp-includes/query.php */ $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this)); /** This filter is documented in wp-includes/query.php */ $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this)); /** This filter is documented in wp-includes/query.php */ $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this)); $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : ''; /** This filter is documented in wp-includes/query.php */ $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this)); $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : ''; /** This filter is documented in wp-includes/query.php */ $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this)); $comments_request = "SELECT {$this->db->comments}.* FROM {$this->db->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}"; $comments = $this->db->get_results($comments_request); // Convert to WP_Comment $this->comments = array_map('get_comment', $comments); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if (!empty($this->posts) && ($this->is_single || $this->is_page)) { $status = get_post_status($this->posts[0]); if ('attachment' === $this->posts[0]->post_type && 0 === (int) $this->posts[0]->post_parent) { $this->is_page = false; $this->is_single = true; $this->is_attachment = true; } $post_status_obj = get_post_status_object($status); // If the post_status was specifically requested, let it pass through. if (!$post_status_obj->public && !in_array($status, $q_status)) { if (!is_user_logged_in()) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ($post_status_obj->protected) { // User must have edit permissions on the draft to preview. if (!current_user_can($edit_cap, $this->posts[0]->ID)) { $this->posts = array(); } else { $this->is_preview = true; if ('future' != $status) { $this->posts[0]->post_date = current_time('mysql'); } } } elseif ($post_status_obj->private) { if (!current_user_can($read_cap, $this->posts[0]->ID)) { $this->posts = array(); } } else { $this->posts = array(); } } } if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) { /** * Filters the single post for preview mode. * * @since 2.7.0 * * @param WP_Post $post_preview The Post object. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->posts[0] = get_post(apply_filters_ref_array('the_preview', array($this->posts[0], &$this))); } } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ($i = 0; $i < $num_posts; $i++) { if (in_array($this->posts[$i]->ID, $sticky_posts)) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset($sticky_posts[$offset]); } } // If any posts have been excluded specifically, Ignore those that are sticky. if (!empty($sticky_posts) && !empty($q['post__not_in'])) { $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); } // Fetch sticky posts that weren't in the query results if (!empty($sticky_posts)) { $stickies = get_posts(array('post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true)); foreach ($stickies as $sticky_post) { array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); $sticky_offset++; } } } // If comments have been fetched as part of the query, make sure comment meta lazy-loading is set up. if (!empty($this->comments)) { wp_queue_comments_for_comment_meta_lazyload($this->comments); } if (!$q['suppress_filters']) { /** * Filters the array of retrieved posts after they've been fetched and * internally processed. * * @since 1.5.0 * * @param array $posts The array of retrieved posts. * @param WP_Query &$this The WP_Query instance (passed by reference). */ $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this)); } // Ensure that any posts added/modified via one of the filters above are // of the type WP_Post and are filtered. if ($this->posts) { $this->post_count = count($this->posts); $this->posts = array_map('get_post', $this->posts); if ($q['cache_results']) { update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); } $this->post = reset($this->posts); } else { $this->post_count = 0; $this->posts = array(); } if ($q['lazy_load_term_meta']) { wp_queue_posts_for_term_meta_lazyload($this->posts); } return $this->posts; }
function _mpp_update_post_caches($post_ids, $update_tax = true, $update_meta = true) { global $wpdb; if (empty($post_ids)) { return; } $post_ids = wp_parse_id_list($post_ids); $list = "(" . join(',', $post_ids) . ')'; $query = "SELECT * FROM {$wpdb->posts} WHERE ID IN {$list}"; $posts = $wpdb->get_results($query); update_post_caches($posts, $update_tax, $update_meta); }
<?php get_header(); ?> <div id="content"><!--Conten Begin--> <?php if (have_posts()) { while (have_posts()) { the_post(); update_post_caches($posts); ?> <div class="content" id="post-<?php the_ID(); ?> "> <div class="title"><h2><a href="<?php the_permalink(); ?> " rel="bookmark"><?php the_title(); ?> </a></h2></div> <div class="rich-content"> <?php the_content(__('Read more...', 'isimple')); ?> <?php wp_link_pages(array('before' => '<div class="page-link"><span>' . __('Page', 'twentyeleven') . '</span>', 'after' => '</div><div class="c"></div>', 'link_before' => '<span class="current">', 'link_after' => '</span>')); ?> </div> <div class="under">
function get_posts($args) { global $wpdb; $defaults = array('numberposts' => 5, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' => '', 'post_type' => 'post', 'post_status' => 'publish', 'post_parent' => 0); $r = wp_parse_args($args, $defaults); extract($r, EXTR_SKIP); $numberposts = (int) $numberposts; $offset = (int) $offset; $category = (int) $category; $post_parent = (int) $post_parent; $inclusions = ''; if (!empty($include)) { $offset = 0; //ignore offset, category, exclude, meta_key, and meta_value, post_parent if using include $category = 0; $exclude = ''; $meta_key = ''; $meta_value = ''; $post_parent = 0; $incposts = preg_split('/[\\s,]+/', $include); $numberposts = count($incposts); // only the number of posts included if (count($incposts)) { foreach ($incposts as $incpost) { if (empty($inclusions)) { $inclusions = ' AND ( ID = ' . intval($incpost) . ' '; } else { $inclusions .= ' OR ID = ' . intval($incpost) . ' '; } } } } if (!empty($inclusions)) { $inclusions .= ')'; } $exclusions = ''; if (!empty($exclude)) { $exposts = preg_split('/[\\s,]+/', $exclude); if (count($exposts)) { foreach ($exposts as $expost) { if (empty($exclusions)) { $exclusions = ' AND ( ID <> ' . intval($expost) . ' '; } else { $exclusions .= ' AND ID <> ' . intval($expost) . ' '; } } } } if (!empty($exclusions)) { $exclusions .= ')'; } $query = "SELECT DISTINCT * FROM {$wpdb->posts} "; $query .= empty($category) ? '' : ", {$wpdb->term_relationships}, {$wpdb->term_taxonomy} "; $query .= empty($meta_key) ? '' : ", {$wpdb->postmeta} "; $query .= " WHERE 1=1 "; $query .= empty($post_type) ? '' : "AND post_type = '{$post_type}' "; $query .= empty($post_status) ? '' : "AND post_status = '{$post_status}' "; $query .= "{$exclusions} {$inclusions} "; $query .= empty($category) ? '' : "AND ({$wpdb->posts}.ID = {$wpdb->term_relationships}.object_id AND {$wpdb->term_relationships}.term_taxonomy_id = {$wpdb->term_taxonomy}.term_taxonomy_id AND {$wpdb->term_taxonomy}.term_id = " . $category . ") "; $query .= empty($post_parent) ? '' : "AND {$wpdb->posts}.post_parent = '{$post_parent}' "; $query .= empty($meta_key) | empty($meta_value) ? '' : " AND ({$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '{$meta_key}' AND {$wpdb->postmeta}.meta_value = '{$meta_value}' )"; $query .= " GROUP BY {$wpdb->posts}.ID ORDER BY " . $orderby . ' ' . $order; if (0 < $numberposts) { $query .= " LIMIT " . $offset . ',' . $numberposts; } $posts = $wpdb->get_results($query); update_post_caches($posts); return $posts; }