protected function get_people($instance) { $args = ['numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC']; if (isset($instance['people_category'])) { $people_cat = get_category_by_path($instance['people_category']); $args['category'] = $people_cat->cat_ID; } $people = get_posts($args); return array_map(function ($p) { return new WidgetPerson($p); }, $people); }
function td_modify_main_query_for_category_page($query) { //checking for category page and main query if (!is_admin() and is_category() and $query->is_main_query()) { // get the category object - with or without permalinks if (empty($query->query_vars['cat'])) { td_global::$current_category_obj = get_category_by_path(get_query_var('category_name'), false); // when we have permalinks, we have to get the category object like this. } else { td_global::$current_category_obj = get_category($query->query_vars['cat']); } // we are on a category page with an ID that doesn't exists - wp will show a 404 and we do nothing if (is_null(td_global::$current_category_obj)) { return; } //get the number of page where on $paged = get_query_var('paged'); //get the `filter_by` URL($_GET) variable $filter_by = get_query_var('filter_by'); //get the limit of posts on the category page $limit = get_option('posts_per_page'); //echo $filter_by; switch ($filter_by) { case 'featured': //get the category object $query->set('category_name', td_global::$current_category_obj->slug); $query->set('cat', get_cat_ID(TD_FEATURED_CAT)); //add the fetured cat break; case 'popular': $query->set('meta_key', td_page_views::$post_view_counter_key); $query->set('orderby', 'meta_value_num'); $query->set('order', 'DESC'); break; case 'popular7': $query->set('meta_key', td_page_views::$post_view_counter_7_day_total); $query->set('orderby', 'meta_value_num'); $query->set('order', 'DESC'); break; case 'review_high': $query->set('meta_key', td_review::$td_review_key); $query->set('orderby', 'meta_value_num'); $query->set('order', 'DESC'); break; case 'random_posts': $query->set('orderby', 'rand'); break; } //end switch // how many posts are we showing in the big grid for this category $offset = td_api_category_top_posts_style::_helper_get_posts_shown_in_the_loop(); // offset + custom pagination - if we have offset, WordPress overwrites the pagination and works with offset + limit if (empty($query->is_feed)) { if (!empty($offset) and $paged > 1) { $query->set('offset', $offset + ($paged - 1) * $limit); } else { $query->set('offset', $offset); } } //print_r($query); } //end if main 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; }
/** * Validate get_category_by_path function */ function test_get_category_by_path() { // create Test Categories $root_id = $this->factory->category->create( array( 'slug' => 'root', ) ); $root_cat_id = $this->factory->category->create( array( 'slug' => 'cat', 'parent' => $root_id ) ); $root_cat_cat_id = $this->factory->category->create( array( 'slug' => 'cat', //note this is modified on create 'parent' => $root_cat_id ) ); $root_path_id = $this->factory->category->create( array( 'slug' => 'path', 'parent' => $root_id ) ); $root_path_cat_id = $this->factory->category->create( array( 'slug' => 'cat', //note this is modified on create 'parent' => $root_path_id ) ); $root_level_id = $this->factory->category->create( array( 'slug' => 'level-1', 'parent' => $root_id ) ); $root_level_cat_id = $this->factory->category->create( array( 'slug' => 'cat', //note this is modified on create 'parent' => $root_level_id ) ); // Validate Full Match $ret_cat = get_category_by_path( '/root/level-1', true ); $this->assertEquals( $root_level_id, $ret_cat->term_id ); $this->assertNull( get_category_by_path( 'level-1', true ) ); $this->assertNull( get_category_by_path( 'nocat/nocat/', true) ); // Validate Partial Match $ret_cat = get_category_by_path( 'level-1', false ); $this->assertEquals( $root_level_id, $ret_cat->term_id ); $ret_cat = get_category_by_path( 'root/cat/level-1', false ); $this->assertEquals( $root_level_id, $ret_cat->term_id ); $ret_cat = get_category_by_path( 'root$2Fcat%20%2Flevel-1', false ); $this->assertEquals( $root_level_id, $ret_cat->term_id ); $this->assertNull( get_category_by_path( 'nocat/nocat/', false) ); }
<?php get_header(); ?> <section style="border-bottom:none;"> <?php $url = sf_get_current_url('base'); $category = get_category_by_path($url, false); ?> <h2><?php echo $category->name; ?> </h2> <?php $query = new WP_query('post_type=partenariat'); //Looking for children articles while ($query->have_posts()) { ?> <?php $query->the_post(); ?> <div class="partenariat"> <p class="partenariat__title"> <?php the_title(); ?> </p> <div class="partenariat__content"> <div class="partenariat__description"> <?php if (!!get_field('img')) {
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 td_modify_main_query_for_category_page($query) { //checking for category page and main query if (!is_admin() and is_category() and $query->is_main_query()) { //get the number of page where on $paged = get_query_var('paged'); //get the `filter_by` URL($_GET) variable $filter_by = get_query_var('filter_by'); //get the limit of posts on the category page $limit = get_option('posts_per_page'); // get the category object - with or without permalinks if (empty($query->query_vars['cat'])) { $td_current_category_obj = get_category_by_path(get_query_var('category_name'), false); // when we have permalinks, we have to get the category object like this. } else { $td_current_category_obj = get_category($query->query_vars['cat']); } //if this is `yes` then do not show the big grid $category_big_grid_hide_option = td_util::get_category_option($td_current_category_obj->cat_ID, 'tdc_slider'); //offset is hardcoded because of big grid $offset = 0; if ($category_big_grid_hide_option != 'yes') { $offset = 5; } //echo $filter_by; switch ($filter_by) { case 'featured': //get the category object $query->set('category_name', $td_current_category_obj->slug); $query->set('cat', get_cat_ID(TD_FEATURED_CAT)); //add the fetured cat break; case 'popular': $query->set('meta_key', td_page_views::$post_view_counter_key); $query->set('orderby', 'meta_value_num'); $query->set('order', 'DESC'); break; case 'popular7': $query->set('meta_key', td_page_views::$post_view_counter_7_day_total); $query->set('orderby', 'meta_value_num'); $query->set('order', 'DESC'); break; case 'review_high': $query->set('meta_key', td_review::$td_review_key); $query->set('orderby', 'meta_value_num'); $query->set('order', 'DESC'); break; case 'random_posts': $query->set('orderby', 'rand'); break; } //end switch // offset + custom pagination - if we have offset, wordpress overwrites the pagination and works with offset + limit if (!empty($offset) and $paged > 1) { $query->set('offset', $offset + ($paged - 1) * $limit); } else { $query->set('offset', $offset); } //print_r($query); } //end if main query }
/** * Redirects incoming links to the proper URL based on the site url. * * Search engines consider www.somedomain.com and somedomain.com to be two * different URLs when they both go to the same location. This SEO enhancement * prevents penalty for duplicate content by redirecting all incoming links to * one or the other. * * Prevents redirection for feeds, trackbacks, searches, comment popup, and * admin URLs. Does not redirect on non-pretty-permalink-supporting IIS 7+, * page/post previews, WP admin, Trackbacks, robots.txt, searches, or on POST * requests. * * Will also attempt to find the correct link when a user enters a URL that does * not exist based on exact WordPress query. Will instead try to parse the URL * or query in an attempt to figure the correct page to go to. * * @since 2.3.0 * * @global WP_Rewrite $wp_rewrite * @global bool $is_IIS * @global WP_Query $wp_query * @global wpdb $wpdb WordPress database abstraction object. * * @param string $requested_url Optional. The URL that was requested, used to * figure if redirect is needed. * @param bool $do_redirect Optional. Redirect to the new URL. * @return string|void The string of the URL, if redirect needed. */ function redirect_canonical($requested_url = null, $do_redirect = true) { global $wp_rewrite, $is_IIS, $wp_query, $wpdb, $wp; if (isset($_SERVER['REQUEST_METHOD']) && !in_array(strtoupper($_SERVER['REQUEST_METHOD']), array('GET', 'HEAD'))) { return; } // If we're not in wp-admin and the post has been published and preview nonce // is non-existent or invalid then no need for preview in query if (is_preview() && get_query_var('p') && 'publish' == get_post_status(get_query_var('p'))) { if (!isset($_GET['preview_id']) || !isset($_GET['preview_nonce']) || !wp_verify_nonce($_GET['preview_nonce'], 'post_preview_' . (int) $_GET['preview_id'])) { $wp_query->is_preview = false; } } if (is_trackback() || is_search() || is_comments_popup() || is_admin() || is_preview() || is_robots() || $is_IIS && !iis7_supports_permalinks()) { return; } if (!$requested_url && isset($_SERVER['HTTP_HOST'])) { // build the URL in the address bar $requested_url = is_ssl() ? 'https://' : 'http://'; $requested_url .= $_SERVER['HTTP_HOST']; $requested_url .= $_SERVER['REQUEST_URI']; } $original = @parse_url($requested_url); if (false === $original) { return; } $redirect = $original; $redirect_url = false; // Notice fixing if (!isset($redirect['path'])) { $redirect['path'] = ''; } if (!isset($redirect['query'])) { $redirect['query'] = ''; } // If the original URL ended with non-breaking spaces, they were almost // certainly inserted by accident. Let's remove them, so the reader doesn't // see a 404 error with no obvious cause. $redirect['path'] = preg_replace('|(%C2%A0)+$|i', '', $redirect['path']); // It's not a preview, so remove it from URL if (get_query_var('preview')) { $redirect['query'] = remove_query_arg('preview', $redirect['query']); } if (is_feed() && ($id = get_query_var('p'))) { if ($redirect_url = get_post_comments_feed_link($id, get_query_var('feed'))) { $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type', 'feed'), $redirect_url); $redirect['path'] = parse_url($redirect_url, PHP_URL_PATH); } } if (is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p'))) { $vars = $wpdb->get_results($wpdb->prepare("SELECT post_type, post_parent FROM {$wpdb->posts} WHERE ID = %d", $id)); if (isset($vars[0]) && ($vars = $vars[0])) { if ('revision' == $vars->post_type && $vars->post_parent > 0) { $id = $vars->post_parent; } if ($redirect_url = get_permalink($id)) { $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url); } } } // These tests give us a WP-generated permalink if (is_404()) { // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's $id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id')); if ($id && ($redirect_post = get_post($id))) { $post_type_obj = get_post_type_object($redirect_post->post_type); if ($post_type_obj->public) { $redirect_url = get_permalink($redirect_post); $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url); } } if (get_query_var('day') && get_query_var('monthnum') && get_query_var('year')) { $year = get_query_var('year'); $month = get_query_var('monthnum'); $day = get_query_var('day'); $date = sprintf('%04d-%02d-%02d', $year, $month, $day); if (!wp_checkdate($month, $day, $year, $date)) { $redirect_url = get_month_link($year, $month); $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum', 'day'), $redirect_url); } } elseif (get_query_var('monthnum') && get_query_var('year') && 12 < get_query_var('monthnum')) { $redirect_url = get_year_link(get_query_var('year')); $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('year', 'monthnum'), $redirect_url); } if (!$redirect_url) { if ($redirect_url = redirect_guess_404_permalink()) { $redirect['query'] = _remove_qs_args_if_not_in_url($redirect['query'], array('page', 'feed', 'p', 'page_id', 'attachment_id', 'pagename', 'name', 'post_type'), $redirect_url); } } if (get_query_var('page') && $wp_query->post && false !== strpos($wp_query->post->post_content, '<!--nextpage-->')) { $redirect['path'] = rtrim($redirect['path'], (int) get_query_var('page') . '/'); $redirect['query'] = remove_query_arg('page', $redirect['query']); $redirect_url = get_permalink($wp_query->post->ID); } } elseif (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) { // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101 if (is_attachment() && !array_diff(array_keys($wp->query_vars), array('attachment', 'attachment_id')) && !$redirect_url) { if (!empty($_GET['attachment_id'])) { $redirect_url = get_attachment_link(get_query_var('attachment_id')); if ($redirect_url) { $redirect['query'] = remove_query_arg('attachment_id', $redirect['query']); } } else { $redirect_url = get_attachment_link(); } } elseif (is_single() && !empty($_GET['p']) && !$redirect_url) { if ($redirect_url = get_permalink(get_query_var('p'))) { $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']); } } elseif (is_single() && !empty($_GET['name']) && !$redirect_url) { if ($redirect_url = get_permalink($wp_query->get_queried_object_id())) { $redirect['query'] = remove_query_arg('name', $redirect['query']); } } elseif (is_page() && !empty($_GET['page_id']) && !$redirect_url) { if ($redirect_url = get_permalink(get_query_var('page_id'))) { $redirect['query'] = remove_query_arg('page_id', $redirect['query']); } } elseif (is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && !$redirect_url) { $redirect_url = home_url('/'); } elseif (is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && !$redirect_url) { if ($redirect_url = get_permalink(get_option('page_for_posts'))) { $redirect['query'] = remove_query_arg('page_id', $redirect['query']); } } elseif (!empty($_GET['m']) && (is_year() || is_month() || is_day())) { $m = get_query_var('m'); switch (strlen($m)) { case 4: // Yearly $redirect_url = get_year_link($m); break; case 6: // Monthly $redirect_url = get_month_link(substr($m, 0, 4), substr($m, 4, 2)); break; case 8: // Daily $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2)); break; } if ($redirect_url) { $redirect['query'] = remove_query_arg('m', $redirect['query']); } // now moving on to non ?m=X year/month/day links } elseif (is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day'])) { if ($redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'))) { $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']); } } elseif (is_month() && get_query_var('year') && !empty($_GET['monthnum'])) { if ($redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum'))) { $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']); } } elseif (is_year() && !empty($_GET['year'])) { if ($redirect_url = get_year_link(get_query_var('year'))) { $redirect['query'] = remove_query_arg('year', $redirect['query']); } } elseif (is_author() && !empty($_GET['author']) && preg_match('|^[0-9]+$|', $_GET['author'])) { $author = get_userdata(get_query_var('author')); if (false !== $author && $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_author = %d AND {$wpdb->posts}.post_status = 'publish' LIMIT 1", $author->ID))) { if ($redirect_url = get_author_posts_url($author->ID, $author->user_nicename)) { $redirect['query'] = remove_query_arg('author', $redirect['query']); } } } elseif (is_category() || is_tag() || is_tax()) { // Terms (Tags/categories) $term_count = 0; foreach ($wp_query->tax_query->queried_terms as $tax_query) { $term_count += count($tax_query['terms']); } $obj = $wp_query->get_queried_object(); if ($term_count <= 1 && !empty($obj->term_id) && ($tax_url = get_term_link((int) $obj->term_id, $obj->taxonomy)) && !is_wp_error($tax_url)) { if (!empty($redirect['query'])) { // Strip taxonomy query vars off the url. $qv_remove = array('term', 'taxonomy'); if (is_category()) { $qv_remove[] = 'category_name'; $qv_remove[] = 'cat'; } elseif (is_tag()) { $qv_remove[] = 'tag'; $qv_remove[] = 'tag_id'; } else { // Custom taxonomies will have a custom query var, remove those too: $tax_obj = get_taxonomy($obj->taxonomy); if (false !== $tax_obj->query_var) { $qv_remove[] = $tax_obj->query_var; } } $rewrite_vars = array_diff(array_keys($wp_query->query), array_keys($_GET)); if (!array_diff($rewrite_vars, array_keys($_GET))) { // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET $redirect['query'] = remove_query_arg($qv_remove, $redirect['query']); //Remove all of the per-tax qv's // Create the destination url for this taxonomy $tax_url = parse_url($tax_url); if (!empty($tax_url['query'])) { // Taxonomy accessible via ?taxonomy=..&term=.. or any custom qv.. parse_str($tax_url['query'], $query_vars); $redirect['query'] = add_query_arg($query_vars, $redirect['query']); } else { // Taxonomy is accessible via a "pretty-URL" $redirect['path'] = $tax_url['path']; } } else { // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite foreach ($qv_remove as $_qv) { if (isset($rewrite_vars[$_qv])) { $redirect['query'] = remove_query_arg($_qv, $redirect['query']); } } } } } } elseif (is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false && ($cat = get_query_var('category_name'))) { $category = get_category_by_path($cat); $post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids')); if (!$category || is_wp_error($category) || !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms)) { $redirect_url = get_permalink($wp_query->get_queried_object_id()); } } // Post Paging if (is_singular() && !is_front_page() && get_query_var('page')) { if (!$redirect_url) { $redirect_url = get_permalink(get_queried_object_id()); } $redirect_url = trailingslashit($redirect_url) . user_trailingslashit(get_query_var('page'), 'single_paged'); $redirect['query'] = remove_query_arg('page', $redirect['query']); } // paging and feeds if (get_query_var('paged') || is_feed() || get_query_var('cpage')) { while (preg_match("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", $redirect['path']) || preg_match('#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path']) || preg_match("#/{$wp_rewrite->comments_pagination_base}-[0-9]+(/+)?\$#", $redirect['path'])) { // Strip off paging and feed $redirect['path'] = preg_replace("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", '/', $redirect['path']); // strip off any existing paging $redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings $redirect['path'] = preg_replace("#/{$wp_rewrite->comments_pagination_base}-[0-9]+?(/+)?\$#", '/', $redirect['path']); // strip off any existing comment paging } $addl_path = ''; if (is_feed() && in_array(get_query_var('feed'), $wp_rewrite->feeds)) { $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : ''; if (!is_singular() && get_query_var('withcomments')) { $addl_path .= 'comments/'; } if ('rss' == get_default_feed() && 'feed' == get_query_var('feed') || 'rss' == get_query_var('feed')) { $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == 'rss2' ? '' : 'rss2'), 'feed'); } else { $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ? '' : get_query_var('feed')), 'feed'); } $redirect['query'] = remove_query_arg('feed', $redirect['query']); } elseif (is_feed() && 'old' == get_query_var('feed')) { $old_feed_files = array('wp-atom.php' => 'atom', 'wp-commentsrss2.php' => 'comments_rss2', 'wp-feed.php' => get_default_feed(), 'wp-rdf.php' => 'rdf', 'wp-rss.php' => 'rss2', 'wp-rss2.php' => 'rss2'); if (isset($old_feed_files[basename($redirect['path'])])) { $redirect_url = get_feed_link($old_feed_files[basename($redirect['path'])]); wp_redirect($redirect_url, 301); die; } } if (get_query_var('paged') > 0) { $paged = get_query_var('paged'); $redirect['query'] = remove_query_arg('paged', $redirect['query']); if (!is_feed()) { if ($paged > 1 && !is_single()) { $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit("{$wp_rewrite->pagination_base}/{$paged}", 'paged'); } elseif (!is_single()) { $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : ''; } } elseif ($paged > 1) { $redirect['query'] = add_query_arg('paged', $paged, $redirect['query']); } } if (get_option('page_comments') && ('newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 || 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1)) { $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit($wp_rewrite->comments_pagination_base . '-' . get_query_var('cpage'), 'commentpaged'); $redirect['query'] = remove_query_arg('cpage', $redirect['query']); } $redirect['path'] = user_trailingslashit(preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/?$|', '/', $redirect['path'])); // strip off trailing /index.php/ if (!empty($addl_path) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/' . $wp_rewrite->index . '/') === false) { $redirect['path'] = trailingslashit($redirect['path']) . $wp_rewrite->index . '/'; } if (!empty($addl_path)) { $redirect['path'] = trailingslashit($redirect['path']) . $addl_path; } $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path']; } if ('wp-register.php' == basename($redirect['path'])) { if (is_multisite()) { /** This filter is documented in wp-login.php */ $redirect_url = apply_filters('wp_signup_location', network_site_url('wp-signup.php')); } else { $redirect_url = wp_registration_url(); } wp_redirect($redirect_url, 301); die; } } // tack on any additional query vars $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']); if ($redirect_url && !empty($redirect['query'])) { parse_str($redirect['query'], $_parsed_query); $redirect = @parse_url($redirect_url); if (!empty($_parsed_query['name']) && !empty($redirect['query'])) { parse_str($redirect['query'], $_parsed_redirect_query); if (empty($_parsed_redirect_query['name'])) { unset($_parsed_query['name']); } } $_parsed_query = rawurlencode_deep($_parsed_query); $redirect_url = add_query_arg($_parsed_query, $redirect_url); } if ($redirect_url) { $redirect = @parse_url($redirect_url); } // www.example.com vs example.com $user_home = @parse_url(home_url()); if (!empty($user_home['host'])) { $redirect['host'] = $user_home['host']; } if (empty($user_home['path'])) { $user_home['path'] = '/'; } // Handle ports if (!empty($user_home['port'])) { $redirect['port'] = $user_home['port']; } else { unset($redirect['port']); } // trailing /index.php $redirect['path'] = preg_replace('|/' . preg_quote($wp_rewrite->index, '|') . '/*?$|', '/', $redirect['path']); // Remove trailing spaces from the path $redirect['path'] = preg_replace('#(%20| )+$#', '', $redirect['path']); if (!empty($redirect['query'])) { // Remove trailing spaces from certain terminating query string args $redirect['query'] = preg_replace('#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query']); // Clean up empty query strings $redirect['query'] = trim(preg_replace('#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&'); // Redirect obsolete feeds $redirect['query'] = preg_replace('#(^|&)feed=rss(&|$)#', '$1feed=rss2$2', $redirect['query']); // Remove redundant leading ampersands $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']); } // strip /index.php/ when we're not using PATHINFO permalinks if (!$wp_rewrite->using_index_permalinks()) { $redirect['path'] = str_replace('/' . $wp_rewrite->index . '/', '/', $redirect['path']); } // trailing slashes if (is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || is_front_page() && get_query_var('paged') > 1)) { $user_ts_type = ''; if (get_query_var('paged') > 0) { $user_ts_type = 'paged'; } else { foreach (array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type) { $func = 'is_' . $type; if (call_user_func($func)) { $user_ts_type = $type; break; } } } $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type); } elseif (is_front_page()) { $redirect['path'] = trailingslashit($redirect['path']); } // Strip multiple slashes out of the URL if (strpos($redirect['path'], '//') > -1) { $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']); } // Always trailing slash the Front Page URL if (trailingslashit($redirect['path']) == trailingslashit($user_home['path'])) { $redirect['path'] = trailingslashit($redirect['path']); } // Ignore differences in host capitalization, as this can lead to infinite redirects // Only redirect no-www <=> yes-www if (strtolower($original['host']) == strtolower($redirect['host']) || strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host'])) { $redirect['host'] = $original['host']; } $compare_original = array($original['host'], $original['path']); if (!empty($original['port'])) { $compare_original[] = $original['port']; } if (!empty($original['query'])) { $compare_original[] = $original['query']; } $compare_redirect = array($redirect['host'], $redirect['path']); if (!empty($redirect['port'])) { $compare_redirect[] = $redirect['port']; } if (!empty($redirect['query'])) { $compare_redirect[] = $redirect['query']; } if ($compare_original !== $compare_redirect) { $redirect_url = $redirect['scheme'] . '://' . $redirect['host']; if (!empty($redirect['port'])) { $redirect_url .= ':' . $redirect['port']; } $redirect_url .= $redirect['path']; if (!empty($redirect['query'])) { $redirect_url .= '?' . $redirect['query']; } } if (!$redirect_url || $redirect_url == $requested_url) { return; } // Hex encoded octets are case-insensitive. if (false !== strpos($requested_url, '%')) { if (!function_exists('lowercase_octets')) { function lowercase_octets($matches) { return strtolower($matches[0]); } } $requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url); } /** * Filter the canonical redirect URL. * * Returning false to this filter will cancel the redirect. * * @since 2.3.0 * * @param string $redirect_url The redirect URL. * @param string $requested_url The requested URL. */ $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url); // yes, again -- in case the filter aborted the request if (!$redirect_url || $redirect_url == $requested_url) { return; } if ($do_redirect) { // protect against chained redirects if (!redirect_canonical($redirect_url, false)) { wp_redirect($redirect_url, 301); exit; } else { // Debug // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) ); return; } } else { return $redirect_url; } }
/** * hide protected post/pages from apearing in list/feeds etc * * @param object $query * @return object $query * @since 1.0 */ function mgm_hide_protected($query) { global $post; // do not run when admin section loaded #1459 if (is_admin()) { return $query; } // if loading from feed if (is_feed() && isset($_GET['token']) && mgm_use_rss_token()) { // get user by rss token, only for feed $user = mgm_get_user_by_token(strip_tags($_GET['token'])); } else { // current user if (function_exists('wp_get_current_user')) { $user = wp_get_current_user(); } else { global $user_ID; // pick $user = get_userdata($user_ID); } } // get system $system_obj = mgm_get_class('system'); // flag $run_cat_notin = $run_term_notin = false; // user is not a spider if (!mgm_is_a_bot()) { // hide post $hide_posts = mgm_content_exclude_by_user($user->ID, 'post'); // hide post // set filter if (is_array($hide_posts) && !empty($hide_posts)) { $query->set('post__not_in', array_unique($hide_posts)); // set negation } // hide cats $hide_cats = mgm_content_exclude_by_user($user->ID, 'category'); //hide cats // set filter if (is_array($hide_cats) && !empty($hide_cats)) { // flag $run_cat_notin = true; //category not found redirection //skip admin and home //consider only posts: if (!is_super_admin() && !is_home() && is_single()) { // url $category_access_redirect_url = $system_obj->get_setting('category_access_redirect_url'); //skip if same url: if (!empty($category_access_redirect_url) && trailingslashit(mgm_current_url()) != trailingslashit($category_access_redirect_url)) { //check returned category ids belongs to the loaded post: if (isset($post->ID) && is_numeric($post->ID)) { //get post categories $post_cats = wp_get_post_categories($post->ID); // loop foreach ($post_cats as $cat) { //redirect if post category exists in blocked categories if (in_array($cat, $hide_cats)) { //redirect: mgm_redirect($category_access_redirect_url); exit; } } } } } //issue#: 510 if ($run_cat_notin) { // set $query->set('category__not_in', array_unique($hide_cats)); // set negation // issue#: 510 if (substr(get_bloginfo('version'), 0, 3) > 3.0 && !is_page()) { //Note: selectively attach the filter to not apply in other scenarios //issue #1600 $post_name = $query->query_vars['name']; if (empty($post_name)) { $current_uri = trim($_SERVER['REQUEST_URI']); $uri = explode('?', $current_uri); $uriArr = explode('/', $uri[0]); if (!empty($uriArr)) { $post_name = $uriArr[1]; } } $member = mgm_get_member($user->ID); $membership_type = $member->membership_type; $membership_type = empty($membership_type) ? 'guest' : $membership_type; $arr_memberships = mgm_get_subscribed_membershiptypes($user->ID, $member); if (!in_array($membership_type, $arr_memberships)) { $arr_memberships[] = $membership_type; } $accessible = false; $post_data = mgm_get_post_data_by_name($post_name); // check found if (isset($post_data->ID)) { $post_obj = mgm_get_post($post_data->ID); if (count(array_intersect($post_obj->access_membership_types, $arr_memberships)) > 0) { $accessible = true; } } //not accessible add filter if (!$accessible) { //to filter posts as per category__not_in values add_filter('posts_search', 'mgm_attach_category_not_in'); } } } // if on category archive listing page: check cateory is accessible, if not redirect to category_access_redirect_url setting url if (!is_super_admin() && !is_home() && is_category()) { // url $the_url = mgm_current_url(); //get archived category details $loaded_cat = get_category_by_path($the_url, false); //getting subcategory by path - issue #1578 if (empty($loaded_cat)) { $flag = false; $url_segments = preg_split('#/#', $the_url); foreach ($url_segments as $key => $url_segment) { if (strtolower($url_segment) == 'category') { $flag = $key; } } if ($flag) { if (!empty($url_segments[$flag + 2])) { $slug = $url_segments[$flag + 2]; $loaded_cat = get_category_by_slug($slug); } } } // url if (!isset($category_access_redirect_url)) { $category_access_redirect_url = $system_obj->get_setting('category_access_redirect_url'); } // issue #: 657 // if the loaded category cannot be accessed by the user, and if category_access_redirect_url is set, redirect if (isset($loaded_cat->cat_ID) && in_array($loaded_cat->cat_ID, $hide_cats) && !empty($category_access_redirect_url) && trailingslashit($the_url) != trailingslashit($category_access_redirect_url)) { // redirect: mgm_redirect($category_access_redirect_url); exit; } } } } // endif // hide terms $hide_terms = mgm_content_exclude_by_user($user->ID, 'taxonomy'); //hide terms // set filter if (is_array($hide_terms) && !empty($hide_terms)) { // flag $run_term_notin = true; // set filter $query->set('tag__not_in', array_unique($hide_terms)); // set negation // set in search if (substr(get_bloginfo('version'), 0, 3) > 3.0 && !is_page()) { //note: selectively attach the filter to not apply in other scenarios add_filter('posts_search', 'mgm_attach_tag_not_in'); //to filter posts as per tag__not_in values } } // term check if ($run_cat_notin || $run_term_notin) { add_filter('list_terms_exclusions', 'mgm_exclude_terms'); // terms } // return return $query; }
function customizer_wrapper_preview_type($previewed_url = null) { //make this usable on front-end templating and backend-admin //by also handling the easy cases: regular templating if (true === is_single()) { return array('id' => get_query_var('p'), 'type' => 'single'); } else { if (true === is_home()) { return array('id' => null, 'type' => 'home'); } else { if (true === is_category()) { return array('id' => get_query_var('cat'), 'type' => 'category'); } else { if (true === is_author()) { return array('id' => get_query_var('author'), 'type' => 'author'); } } } } if (null === $previewed_url) { //the harder stuff: ?url= parameter //first step, figure out the url $previewed_url = $_GET['url']; if (empty($previewed_url)) { $full = $_SERVER['HTTP_REFERER']; $parsed = parse_url($full); $query = $parsed['query']; $args = array(); parse_str($query, $args); $previewed_url = $args['url']; } } $previewed_url = apply_filters('customizer_demo_preview_url', $previewed_url); if (empty($previewed_url)) { return apply_filters('customizer_wrapper_preview_type', array('url' => null, 'id' => null, 'type' => null)); } //next step: figure out what kind of page the //$previewed_url represents $object_id = null; $post_id = null; //check if it's a post $post_id = url_to_postid($previewed_url); if (0 === $post_id) { //last attempt to parse (recipes fail url_to_postid) $parsed = parse_url($previewed_url); $matches = array(); //catch ?p=123 (guid-like) permalinks preg_match_all('/^\\/(\\d{1,})\\//', $parsed['path'], $matches); if (isset($matches[1]) && isset($matches[1][0])) { $post_id = $matches[1][0]; } } if (null !== $post_id && 0 !== $post_id) { $type = 'single'; $object_id = $post_id; } else { //check if it's a category $home_url = get_home_url(); $cat = get_category_by_path(str_replace($home_url, "", $previewed_url), $full_match = true, constant('OBJECT')); if (null !== $cat) { $type = 'category'; $object_id = $cat->ID; } //check if it's a homepage if (null === $type) { if ($previewed_url === $home_url) { $type = 'homepage'; } } } return apply_filters('customizer_wrapper_preview_type', array('url' => $previewed_url, 'id' => $object_id, 'type' => $type)); }
function wk_navigation_display($language, $posts_num, $mode = 1, $page_type = '') { include 'languages/' . $language . '.php'; global $url; global $addon; global $paged; //find from page_type if ($page_type == 'cat') { $cat = get_category_by_path($_SERVER['REQUEST_URI'], false); $posts_num = $cat->count; } if ($mode == 0) { ?> <div id="wp-pagenavi"> <span class="pages"><?php echo $page_txt; ?> <?php echo $paged; ?> <?php echo $from_txt; ?> <?php $last_page = intval($posts_num / 10); $last_page++; echo $last_page; ?> </span> <span class="navi-choices"> <a href="<?php echo $url . $addon; ?> " title="« Πρώτη Σελίδα">« <?php echo $first_txt; ?> </a> <a href="<?php if ($paged <= 2) { echo $url . $addon; } else { $new_paged = $paged - 1; echo $url . 'page/' . $new_paged . '/' . $addon; } ?> ">«</a> <?php if ($paged < 4) { $start = 1; } else { $start = $paged - 1; } if ($last_page - $paged > 3) { $end = $paged + 3; } else { $end = $last_page + 1; } for ($i = $start; $i < $end; $i++) { if ($i == $paged) { ?> <span class="current"><?php echo $paged; ?> </span> <?php } else { ?> <a href="<?php if ($i != 1) { echo $url . 'page/' . $i . '/' . $addon; } else { echo $url . $addon; } ?> " title="<?php echo $i; ?> "><?php echo $i; ?> </a> <?php } } ?> <a href="<?php if ($paged != $last_page) { $new_paged = $paged + 1; echo $url . 'page/' . $new_paged . '/' . $addon; } else { echo $_SERVER['REQUEST_URI']; } ?> ">»</a> <a href="<?php if ($last_page != 1) { echo $url . 'page/' . $last_page . '/' . $addon; } else { echo $url . $addon; } ?> " title="Τελευταία Σελίδα »"><?php echo $last_txt; ?> »</a> </span> <!-- close navi-choices --> </div> <!-- close wp-pagenavi --> <?php } else { ?> <div id="wp-pagenavi"> <span class="pages"><?php echo $page_txt; ?> <?php echo $paged; ?> <?php echo $from_txt; ?> <?php $last_page = intval($posts_num / 10); $last_page++; echo $last_page; ?> </span> <span class="navi-choices"> <a href="<?php echo $url; ?> " title="« Πρώτη Σελίδα">« <?php echo $first_txt; ?> </a> <a href="<?php if ($paged <= 2) { echo $url; } else { $new_paged = $paged - 1; echo $url . '?page=' . $new_paged; } ?> ">«</a> <?php if ($paged < 4) { $start = 1; } else { $start = $paged - 1; } if ($last_page - $paged > 3) { $end = $paged + 3; } else { $end = $last_page + 1; } for ($i = $start; $i < $end; $i++) { if ($i == $paged) { ?> <span class="current"><?php echo $paged; ?> </span> <?php } else { ?> <a href="<?php if ($i != 1) { echo $url . '?page=' . $i; } else { echo $url; } ?> " title="<?php echo $i; ?> "><?php echo $i; ?> </a> <?php } } ?> <a href="<?php if ($paged != $last_page) { $new_paged = $paged + 1; echo $url . '?page=' . $new_paged; } else { echo $_SERVER['REQUEST_URI']; } ?> ">»</a> <a href="<?php if ($last_page != 1) { echo $url . '?page=' . $last_page; } else { echo $url; } ?> " title="Τελευταία Σελίδα »"><?php echo $last_txt; ?> »</a> </span> <!-- close navi-choices --> </div> <!-- close wp-pagenavi --> <?php } }
protected function get_weekdays() { global $week_mapping; $weekdays_cat = get_category_by_path($this->options['weekday_category']); $weekdays = array_map(function ($t) { return get_category($t); }, get_term_children($weekdays_cat->term_id, $weekdays_cat->taxonomy)); $result = []; foreach ($weekdays as $weekday) { $index = $week_mapping[strtoupper($weekday->cat_name)]; $result[$index] = $weekday; } ksort($result); return $result; }
function set_taxonomy_by_permalink($user_category_permalink, $user_category_id) { $permalinkIsTaxonomy = false; $taxonomy = false; $c = get_category_by_path($user_category_permalink, false); //If getting category fails, trying to get custom taxonomy if ($c == NULL) { $c = get_taxonomy_by_path($user_category_permalink); } // So is it a category/taxonomy? Let's also tell the permalink parser we already figured it out if ($c) { $user_category_id = $c->term_id; $permalinkIsTaxonomy = true; $taxonomy = $c->taxonomy; } return array($user_category_id, $permalinkIsTaxonomy, $taxonomy); }
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; }
/** * 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; }
static function get_pagination() { global $wp_query; if (td_global::$current_template == '404') { return; } $pagenavi_options = self::pagenavi_init(); $request = $wp_query->request; $posts_per_page = intval(get_query_var('posts_per_page')); $paged = intval(get_query_var('paged')); $numposts = $wp_query->found_posts; $max_page = $wp_query->max_num_pages; //hack for category pages - pagination if (!is_admin() and is_category()) { // get the category object - with or without permalinks if (empty($wp_query->query_vars['cat'])) { $td_current_category_obj = get_category_by_path(get_query_var('category_name'), false); // when we have permalinks, we have to get the category object like this. } else { $td_current_category_obj = get_category($wp_query->query_vars['cat']); } if (isset($td_current_category_obj->cat_ID)) { $disable_category_big_grid_hide_option = td_util::get_category_option($td_current_category_obj->cat_ID, 'tdc_slider'); } else { $disable_category_big_grid_hide_option = ''; } //check if the slider for this category is enabled or disabled if ($disable_category_big_grid_hide_option != 'yes') { $numposts = $wp_query->found_posts - 5; //5 from big grid $max_page = ceil($numposts / $posts_per_page); } //echo '<br>num posts: '.$numposts; //echo '<br>max pages: '.$max_page; } if (empty($paged) || $paged == 0) { $paged = 1; } $pages_to_show = intval($pagenavi_options['num_pages']); $larger_page_to_show = intval($pagenavi_options['num_larger_page_numbers']); $larger_page_multiple = intval($pagenavi_options['larger_page_numbers_multiple']); $pages_to_show_minus_1 = $pages_to_show - 1; $half_page_start = floor($pages_to_show_minus_1 / 2); $half_page_end = ceil($pages_to_show_minus_1 / 2); $start_page = $paged - $half_page_start; if ($start_page <= 0) { $start_page = 1; } $end_page = $paged + $half_page_end; if ($end_page - $start_page != $pages_to_show_minus_1) { $end_page = $start_page + $pages_to_show_minus_1; } if ($end_page > $max_page) { $start_page = $max_page - $pages_to_show_minus_1; $end_page = $max_page; } if ($start_page <= 0) { $start_page = 1; } $larger_per_page = $larger_page_to_show * $larger_page_multiple; $larger_start_page_start = self::td_round_number($start_page, 10) + $larger_page_multiple - $larger_per_page; $larger_start_page_end = self::td_round_number($start_page, 10) + $larger_page_multiple; $larger_end_page_start = self::td_round_number($end_page, 10) + $larger_page_multiple; $larger_end_page_end = self::td_round_number($end_page, 10) + $larger_per_page; if ($larger_start_page_end - $larger_page_multiple == $start_page) { $larger_start_page_start = $larger_start_page_start - $larger_page_multiple; $larger_start_page_end = $larger_start_page_end - $larger_page_multiple; } if ($larger_start_page_start <= 0) { $larger_start_page_start = $larger_page_multiple; } if ($larger_start_page_end > $max_page) { $larger_start_page_end = $max_page; } if ($larger_end_page_end > $max_page) { $larger_end_page_end = $max_page; } if ($max_page > 1 || intval($pagenavi_options['always_show']) == 1) { $pages_text = str_replace("%CURRENT_PAGE%", number_format_i18n($paged), $pagenavi_options['pages_text']); $pages_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pages_text); echo '<div class="page-nav td-pb-padding-side">'; previous_posts_link($pagenavi_options['prev_text']); if ($start_page >= 2 && $pages_to_show < $max_page) { $first_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pagenavi_options['first_text']); echo '<a href="' . esc_url(get_pagenum_link()) . '" class="first" title="' . $first_page_text . '">' . $first_page_text . '</a>'; if (!empty($pagenavi_options['dotleft_text'])) { echo '<span class="extend">' . $pagenavi_options['dotleft_text'] . '</span>'; } } if ($larger_page_to_show > 0 && $larger_start_page_start > 0 && $larger_start_page_end <= $max_page) { for ($i = $larger_start_page_start; $i < $larger_start_page_end; $i += $larger_page_multiple) { $page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['page_text']); echo '<a href="' . esc_url(get_pagenum_link($i)) . '" class="page" title="' . $page_text . '">' . $page_text . '</a>'; } } for ($i = $start_page; $i <= $end_page; $i++) { if ($i == $paged) { $current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['current_text']); echo '<span class="current">' . $current_page_text . '</span>'; } else { $page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['page_text']); echo '<a href="' . esc_url(get_pagenum_link($i)) . '" class="page" title="' . $page_text . '">' . $page_text . '</a>'; } } if ($larger_page_to_show > 0 && $larger_end_page_start < $max_page) { for ($i = $larger_end_page_start; $i <= $larger_end_page_end; $i += $larger_page_multiple) { $page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $pagenavi_options['page_text']); echo '<a href="' . esc_url(get_pagenum_link($i)) . '" class="page" title="' . $page_text . '">' . $page_text . '</a>'; } } if ($end_page < $max_page) { if (!empty($pagenavi_options['dotright_text'])) { echo '<span class="extend">' . $pagenavi_options['dotright_text'] . '</span>'; } $last_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pagenavi_options['last_text']); echo '<a href="' . esc_url(get_pagenum_link($max_page)) . '" class="last" title="' . $last_page_text . '">' . $last_page_text . '</a>'; } next_posts_link($pagenavi_options['next_text'], $max_page); if (!empty($pages_text)) { echo '<span class="pages">' . $pages_text . '</span>'; } echo '</div>'; } }
/** * Attempts to guess the correct URL from the current URL (that produced a 404) or * the current query variables. * * @since 2.3.0 * @uses $wpdb * * @param string $current_url Optional. The URL that has 404'd. * @return bool|string The correct URL if one is found. False on failure. */ function redirect_guess_404_permalink( $current_url = '' ) { global $wpdb, $wp_rewrite; if ( ! empty( $current_url ) ) $parsed_url = @parse_url( $current_url ); // Attempt to redirect bare category slugs if the permalink structure starts // with the %category% tag. if ( isset( $parsed_url['path'] ) && preg_match( '#^[^%]+%category%#', $wp_rewrite->permalink_structure ) && $cat = get_category_by_path( $parsed_url['path'] ) ) { if ( ! is_wp_error( $cat ) ) return get_term_link( $cat ); } if ( get_query_var('name') ) { $where = $wpdb->prepare("post_name LIKE %s", like_escape( get_query_var('name') ) . '%'); // if any of post_type, year, monthnum, or day are set, use them to refine the query if ( get_query_var('post_type') ) $where .= $wpdb->prepare(" AND post_type = %s", get_query_var('post_type')); else $where .= " AND post_type IN ('" . implode( "', '", get_post_types( array( 'public' => true ) ) ) . "')"; if ( get_query_var('year') ) $where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year')); if ( get_query_var('monthnum') ) $where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum')); if ( get_query_var('day') ) $where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day')); $post_id = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE $where AND post_status = 'publish'"); if ( ! $post_id ) return false; if ( get_query_var( 'feed' ) ) return get_post_comments_feed_link( $post_id, get_query_var( 'feed' ) ); elseif ( get_query_var( 'page' ) ) return trailingslashit( get_permalink( $post_id ) ) . user_trailingslashit( get_query_var( 'page' ), 'single_paged' ); else return get_permalink( $post_id ); } return false; }
/** * Redirects incoming links to the proper URL based on the site url. * * Search engines consider www.somedomain.com and somedomain.com to be two * different URLs when they both go to the same location. This SEO enhancement * prevents penality for duplicate content by redirecting all incoming links to * one or the other. * * Prevents redirection for feeds, trackbacks, searches, comment popup, and * admin URLs. Does not redirect on IIS, page/post previews, and on form data. * * Will also attempt to find the correct link when a user enters a URL that does * not exist based on exact WordPress query. Will instead try to parse the URL * or query in an attempt to figure the correct page to go to. * * @since 2.3.0 * @uses $wp_rewrite * @uses $is_IIS * * @param string $requested_url Optional. The URL that was requested, used to * figure if redirect is needed. * @param bool $do_redirect Optional. Redirect to the new URL. * @return null|false|string Null, if redirect not needed. False, if redirect * not needed or the string of the URL */ function redirect_canonical($requested_url = null, $do_redirect = true) { global $wp_rewrite, $is_IIS, $wp_query, $wpdb; if (is_trackback() || is_search() || is_comments_popup() || is_admin() || !empty($_POST) || is_preview() || is_robots() || $is_IIS) { return; } if (!$requested_url) { // build the URL in the address bar $requested_url = is_ssl() ? 'https://' : 'http://'; $requested_url .= $_SERVER['HTTP_HOST']; $requested_url .= $_SERVER['REQUEST_URI']; } $original = @parse_url($requested_url); if (false === $original) { return; } // Some PHP setups turn requests for / into /index.php in REQUEST_URI // See: http://trac.wordpress.org/ticket/5017 // See: http://trac.wordpress.org/ticket/7173 // Disabled, for now: // $original['path'] = preg_replace('|/index\.php$|', '/', $original['path']); $redirect = $original; $redirect_url = false; // Notice fixing if (!isset($redirect['path'])) { $redirect['path'] = ''; } if (!isset($redirect['query'])) { $redirect['query'] = ''; } if (is_singular() && 1 > $wp_query->post_count && ($id = get_query_var('p'))) { $vars = $wpdb->get_results($wpdb->prepare("SELECT post_type, post_parent FROM {$wpdb->posts} WHERE ID = %d", $id)); if (isset($vars[0]) && ($vars = $vars[0])) { if ('revision' == $vars->post_type && $vars->post_parent > 0) { $id = $vars->post_parent; } if ($redirect_url = get_permalink($id)) { $redirect['query'] = remove_query_arg(array('p', 'page_id', 'attachment_id', 'post_type'), $redirect['query']); } } } // These tests give us a WP-generated permalink if (is_404()) { // Redirect ?page_id, ?p=, ?attachment_id= to their respective url's $id = max(get_query_var('p'), get_query_var('page_id'), get_query_var('attachment_id')); if ($id && ($redirect_post = get_post($id))) { $post_type_obj = get_post_type_object($redirect_post->post_type); if ($post_type_obj->public) { $redirect_url = get_permalink($redirect_post); $redirect['query'] = remove_query_arg(array('p', 'page_id', 'attachment_id', 'post_type'), $redirect['query']); } } if (!$redirect_url) { $redirect_url = redirect_guess_404_permalink(); } } elseif (is_object($wp_rewrite) && $wp_rewrite->using_permalinks()) { // rewriting of old ?p=X, ?m=2004, ?m=200401, ?m=20040101 if (is_attachment() && !empty($_GET['attachment_id']) && !$redirect_url) { if ($redirect_url = get_attachment_link(get_query_var('attachment_id'))) { $redirect['query'] = remove_query_arg('attachment_id', $redirect['query']); } } elseif (is_single() && !empty($_GET['p']) && !$redirect_url) { if ($redirect_url = get_permalink(get_query_var('p'))) { $redirect['query'] = remove_query_arg(array('p', 'post_type'), $redirect['query']); } } elseif (is_single() && !empty($_GET['name']) && !$redirect_url) { if ($redirect_url = get_permalink($wp_query->get_queried_object_id())) { $redirect['query'] = remove_query_arg('name', $redirect['query']); } } elseif (is_page() && !empty($_GET['page_id']) && !$redirect_url) { if ($redirect_url = get_permalink(get_query_var('page_id'))) { $redirect['query'] = remove_query_arg('page_id', $redirect['query']); } } elseif (is_page() && !is_feed() && isset($wp_query->queried_object) && 'page' == get_option('show_on_front') && $wp_query->queried_object->ID == get_option('page_on_front') && !$redirect_url) { $redirect_url = home_url('/'); } elseif (is_home() && !empty($_GET['page_id']) && 'page' == get_option('show_on_front') && get_query_var('page_id') == get_option('page_for_posts') && !$redirect_url) { if ($redirect_url = get_permalink(get_option('page_for_posts'))) { $redirect['query'] = remove_query_arg('page_id', $redirect['query']); } } elseif (!empty($_GET['m']) && (is_year() || is_month() || is_day())) { $m = get_query_var('m'); switch (strlen($m)) { case 4: // Yearly $redirect_url = get_year_link($m); break; case 6: // Monthly $redirect_url = get_month_link(substr($m, 0, 4), substr($m, 4, 2)); break; case 8: // Daily $redirect_url = get_day_link(substr($m, 0, 4), substr($m, 4, 2), substr($m, 6, 2)); break; } if ($redirect_url) { $redirect['query'] = remove_query_arg('m', $redirect['query']); } // now moving on to non ?m=X year/month/day links } elseif (is_day() && get_query_var('year') && get_query_var('monthnum') && !empty($_GET['day'])) { if ($redirect_url = get_day_link(get_query_var('year'), get_query_var('monthnum'), get_query_var('day'))) { $redirect['query'] = remove_query_arg(array('year', 'monthnum', 'day'), $redirect['query']); } } elseif (is_month() && get_query_var('year') && !empty($_GET['monthnum'])) { if ($redirect_url = get_month_link(get_query_var('year'), get_query_var('monthnum'))) { $redirect['query'] = remove_query_arg(array('year', 'monthnum'), $redirect['query']); } } elseif (is_year() && !empty($_GET['year'])) { if ($redirect_url = get_year_link(get_query_var('year'))) { $redirect['query'] = remove_query_arg('year', $redirect['query']); } } elseif (is_author() && !empty($_GET['author']) && preg_match('|^[0-9]+$|', $_GET['author'])) { $author = get_userdata(get_query_var('author')); if (false !== $author && $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE {$wpdb->posts}.post_author = %d AND {$wpdb->posts}.post_status = 'publish' LIMIT 1", $author->ID))) { if ($redirect_url = get_author_posts_url($author->ID, $author->user_nicename)) { $redirect['query'] = remove_query_arg('author', $redirect['query']); } } } elseif (is_category() || is_tag() || is_tax()) { // Terms (Tags/categories) $term_count = 0; foreach ($wp_query->tax_query->queries as $tax_query) { $term_count += count($tax_query['terms']); } $obj = $wp_query->get_queried_object(); if ($term_count <= 1 && !empty($obj->term_id) && ($tax_url = get_term_link((int) $obj->term_id, $obj->taxonomy)) && !is_wp_error($tax_url)) { if (!empty($redirect['query'])) { // Strip taxonomy query vars off the url. $qv_remove = array('term', 'taxonomy'); if (is_category()) { $qv_remove[] = 'category_name'; $qv_remove[] = 'cat'; } elseif (is_tag()) { $qv_remove[] = 'tag'; $qv_remove[] = 'tag_id'; } else { // Custom taxonomies will have a custom query var, remove those too: $tax_obj = get_taxonomy($obj->taxonomy); if (false !== $tax_obj->query_var) { $qv_remove[] = $tax_obj->query_var; } } $rewrite_vars = array_diff(array_keys($wp_query->query), array_keys($_GET)); if (!array_diff($rewrite_vars, array_keys($_GET))) { // Check to see if all the Query vars are coming from the rewrite, none are set via $_GET $redirect['query'] = remove_query_arg($qv_remove, $redirect['query']); //Remove all of the per-tax qv's // Create the destination url for this taxonomy $tax_url = parse_url($tax_url); if (!empty($tax_url['query'])) { // Taxonomy accessable via ?taxonomy=..&term=.. or any custom qv.. parse_str($tax_url['query'], $query_vars); $redirect['query'] = add_query_arg($query_vars, $redirect['query']); } else { // Taxonomy is accessable via a "pretty-URL" $redirect['path'] = $tax_url['path']; } } else { // Some query vars are set via $_GET. Unset those from $_GET that exist via the rewrite foreach ($qv_remove as $_qv) { if (isset($rewrite_vars[$_qv])) { $redirect['query'] = remove_query_arg($_qv, $redirect['query']); } } } } } } elseif (is_single() && strpos($wp_rewrite->permalink_structure, '%category%') !== false) { $category = get_category_by_path(get_query_var('category_name')); $post_terms = wp_get_object_terms($wp_query->get_queried_object_id(), 'category', array('fields' => 'tt_ids')); if (!$category || is_wp_error($category) || !is_wp_error($post_terms) && !empty($post_terms) && !in_array($category->term_taxonomy_id, $post_terms)) { $redirect_url = get_permalink($wp_query->get_queried_object_id()); } } // Post Paging if (is_singular() && get_query_var('page') && $redirect_url) { $redirect_url = trailingslashit($redirect_url) . user_trailingslashit(get_query_var('page'), 'single_paged'); $redirect['query'] = remove_query_arg('page', $redirect['query']); } // paging and feeds if (get_query_var('paged') || is_feed() || get_query_var('cpage')) { while (preg_match("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", $redirect['path']) || preg_match('#/(comments/?)?(feed|rss|rdf|atom|rss2)(/+)?$#', $redirect['path']) || preg_match('#/comment-page-[0-9]+(/+)?$#', $redirect['path'])) { // Strip off paging and feed $redirect['path'] = preg_replace("#/{$wp_rewrite->pagination_base}/?[0-9]+?(/+)?\$#", '/', $redirect['path']); // strip off any existing paging $redirect['path'] = preg_replace('#/(comments/?)?(feed|rss2?|rdf|atom)(/+|$)#', '/', $redirect['path']); // strip off feed endings $redirect['path'] = preg_replace('#/comment-page-[0-9]+?(/+)?$#', '/', $redirect['path']); // strip off any existing comment paging } $addl_path = ''; if (is_feed() && in_array(get_query_var('feed'), $wp_rewrite->feeds)) { $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : ''; if (get_query_var('withcomments')) { $addl_path .= 'comments/'; } $addl_path .= user_trailingslashit('feed/' . (get_default_feed() == get_query_var('feed') || 'feed' == get_query_var('feed') ? '' : get_query_var('feed')), 'feed'); $redirect['query'] = remove_query_arg('feed', $redirect['query']); } if (get_query_var('paged') > 0) { $paged = get_query_var('paged'); $redirect['query'] = remove_query_arg('paged', $redirect['query']); if (!is_feed()) { if ($paged > 1 && !is_single()) { $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit("{$wp_rewrite->pagination_base}/{$paged}", 'paged'); } elseif (!is_single()) { $addl_path = !empty($addl_path) ? trailingslashit($addl_path) : ''; } } elseif ($paged > 1) { $redirect['query'] = add_query_arg('paged', $paged, $redirect['query']); } } if (get_option('page_comments') && ('newest' == get_option('default_comments_page') && get_query_var('cpage') > 0 || 'newest' != get_option('default_comments_page') && get_query_var('cpage') > 1)) { $addl_path = (!empty($addl_path) ? trailingslashit($addl_path) : '') . user_trailingslashit('comment-page-' . get_query_var('cpage'), 'commentpaged'); $redirect['query'] = remove_query_arg('cpage', $redirect['query']); } $redirect['path'] = user_trailingslashit(preg_replace('|/index.php/?$|', '/', $redirect['path'])); // strip off trailing /index.php/ if (!empty($addl_path) && $wp_rewrite->using_index_permalinks() && strpos($redirect['path'], '/index.php/') === false) { $redirect['path'] = trailingslashit($redirect['path']) . 'index.php/'; } if (!empty($addl_path)) { $redirect['path'] = trailingslashit($redirect['path']) . $addl_path; } $redirect_url = $redirect['scheme'] . '://' . $redirect['host'] . $redirect['path']; } } // tack on any additional query vars $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']); if ($redirect_url && !empty($redirect['query'])) { parse_str($redirect['query'], $_parsed_query); $redirect = @parse_url($redirect_url); if (!empty($_parsed_query['name']) && !empty($redirect['query'])) { parse_str($redirect['query'], $_parsed_redirect_query); if (empty($_parsed_redirect_query['name'])) { unset($_parsed_query['name']); } } $redirect_url = add_query_arg($_parsed_query, $redirect_url); } if ($redirect_url) { $redirect = @parse_url($redirect_url); } // www.example.com vs example.com $user_home = @parse_url(home_url()); if (!empty($user_home['host'])) { $redirect['host'] = $user_home['host']; } if (empty($user_home['path'])) { $user_home['path'] = '/'; } // Handle ports if (!empty($user_home['port'])) { $redirect['port'] = $user_home['port']; } else { unset($redirect['port']); } // trailing /index.php $redirect['path'] = preg_replace('|/index.php/*?$|', '/', $redirect['path']); // Remove trailing spaces from the path $redirect['path'] = preg_replace('#(%20| )+$#', '', $redirect['path']); if (!empty($redirect['query'])) { // Remove trailing spaces from certain terminating query string args $redirect['query'] = preg_replace('#((p|page_id|cat|tag)=[^&]*?)(%20| )+$#', '$1', $redirect['query']); // Clean up empty query strings $redirect['query'] = trim(preg_replace('#(^|&)(p|page_id|cat|tag)=?(&|$)#', '&', $redirect['query']), '&'); // Remove redundant leading ampersands $redirect['query'] = preg_replace('#^\\??&*?#', '', $redirect['query']); } // strip /index.php/ when we're not using PATHINFO permalinks if (!$wp_rewrite->using_index_permalinks()) { $redirect['path'] = str_replace('/index.php/', '/', $redirect['path']); } // trailing slashes if (is_object($wp_rewrite) && $wp_rewrite->using_permalinks() && !is_404() && (!is_front_page() || is_front_page() && get_query_var('paged') > 1)) { $user_ts_type = ''; if (get_query_var('paged') > 0) { $user_ts_type = 'paged'; } else { foreach (array('single', 'category', 'page', 'day', 'month', 'year', 'home') as $type) { $func = 'is_' . $type; if (call_user_func($func)) { $user_ts_type = $type; break; } } } $redirect['path'] = user_trailingslashit($redirect['path'], $user_ts_type); } elseif (is_front_page()) { $redirect['path'] = trailingslashit($redirect['path']); } // Strip multiple slashes out of the URL if (strpos($redirect['path'], '//') > -1) { $redirect['path'] = preg_replace('|/+|', '/', $redirect['path']); } // Always trailing slash the Front Page URL if (trailingslashit($redirect['path']) == trailingslashit($user_home['path'])) { $redirect['path'] = trailingslashit($redirect['path']); } // Ignore differences in host capitalization, as this can lead to infinite redirects // Only redirect no-www <=> yes-www if (strtolower($original['host']) == strtolower($redirect['host']) || strtolower($original['host']) != 'www.' . strtolower($redirect['host']) && 'www.' . strtolower($original['host']) != strtolower($redirect['host'])) { $redirect['host'] = $original['host']; } $compare_original = array($original['host'], $original['path']); if (!empty($original['port'])) { $compare_original[] = $original['port']; } if (!empty($original['query'])) { $compare_original[] = $original['query']; } $compare_redirect = array($redirect['host'], $redirect['path']); if (!empty($redirect['port'])) { $compare_redirect[] = $redirect['port']; } if (!empty($redirect['query'])) { $compare_redirect[] = $redirect['query']; } if ($compare_original !== $compare_redirect) { $redirect_url = $redirect['scheme'] . '://' . $redirect['host']; if (!empty($redirect['port'])) { $redirect_url .= ':' . $redirect['port']; } $redirect_url .= $redirect['path']; if (!empty($redirect['query'])) { $redirect_url .= '?' . $redirect['query']; } } if (!$redirect_url || $redirect_url == $requested_url) { return false; } // Hex encoded octets are case-insensitive. if (false !== strpos($requested_url, '%')) { if (!function_exists('lowercase_octets')) { function lowercase_octets($matches) { return strtolower($matches[0]); } } $requested_url = preg_replace_callback('|%[a-fA-F0-9][a-fA-F0-9]|', 'lowercase_octets', $requested_url); } // Note that you can use the "redirect_canonical" filter to cancel a canonical redirect for whatever reason by returning FALSE $redirect_url = apply_filters('redirect_canonical', $redirect_url, $requested_url); if (!$redirect_url || $redirect_url == $requested_url) { // yes, again -- in case the filter aborted the request return false; } if ($do_redirect) { // protect against chained redirects if (!redirect_canonical($redirect_url, false)) { wp_redirect($redirect_url, 301); exit; } else { // Debug // die("1: $redirect_url<br />2: " . redirect_canonical( $redirect_url, false ) ); return false; } } else { return $redirect_url; } }
function wp_leads_get_page_final_id() { global $post; if (!isset($post)) { return; } $current_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $current_url = preg_replace('/\\?.*/', '', $current_url); $page_id = wpl_url_to_postid($current_url); $site_url = get_option('siteurl'); $clean_current_url = rtrim($current_url, "/"); // If homepage if ($clean_current_url === $site_url) { $page_id = get_option('page_on_front'); // } // If category page if (is_category() || is_archive()) { $cat = get_category_by_path(get_query_var('category_name'), false); $page_id = "cat_" . $cat->cat_ID; $post_type = "category"; } // If tag page if (is_tag()) { $page_id = "tag_" . get_query_var('tag_id'); } if (is_home()) { $page_id = get_option('page_for_posts'); } elseif (is_front_page()) { $page_id = get_option('page_on_front'); } if ($page_id === 0) { $page_id = $post->ID; } return $page_id; }
/** * Attempts to guess the correct URL from the current URL (that produced a 404) or * the current query variables. * * @since 2.3.0 * @uses $wpdb * * @param string $current_url Optional. The URL that has 404'd. * @return bool|string The correct URL if one is found. False on failure. */ function redirect_guess_404_permalink($current_url = '') { global $wpdb, $wp_rewrite; if (!empty($current_url)) { $parsed_url = @parse_url($current_url); } // Attempt to redirect bare category slugs if the permalink structure starts // with the %category% tag. if (isset($parsed_url['path']) && preg_match('#^[^%]+%category%#', $wp_rewrite->permalink_structure) && ($cat = get_category_by_path($parsed_url['path']))) { if (!is_wp_error($cat)) { return get_term_link($cat); } } if (get_query_var('name')) { $where = $wpdb->prepare("post_name LIKE %s", like_escape(get_query_var('name')) . '%'); // if any of post_type, year, monthnum, or day are set, use them to refine the query if (get_query_var('post_type')) { $where .= $wpdb->prepare(" AND post_type = %s", get_query_var('post_type')); } if (get_query_var('year')) { $where .= $wpdb->prepare(" AND YEAR(post_date) = %d", get_query_var('year')); } if (get_query_var('monthnum')) { $where .= $wpdb->prepare(" AND MONTH(post_date) = %d", get_query_var('monthnum')); } if (get_query_var('day')) { $where .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", get_query_var('day')); } $post_id = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE {$where} AND post_status = 'publish'"); if (!$post_id) { return false; } return get_permalink($post_id); } return false; }