Ejemplo n.º 1
0
/**
 * Display archive links based on type and format.
 *
 * @since 1.2.0
 *
 * @see get_archives_link()
 *
 * @global wpdb      $wpdb
 * @global WP_Locale $wp_locale
 *
 * @param string|array $args {
 *     Default archive links arguments. Optional.
 *
 *     @type string     $type            Type of archive to retrieve. Accepts 'daily', 'weekly', 'monthly',
 *                                       'yearly', 'postbypost', or 'alpha'. Both 'postbypost' and 'alpha'
 *                                       display the same archive link list as well as post titles instead
 *                                       of displaying dates. The difference between the two is that 'alpha'
 *                                       will order by post title and 'postbypost' will order by post date.
 *                                       Default 'monthly'.
 *     @type string|int $limit           Number of links to limit the query to. Default empty (no limit).
 *     @type string     $format          Format each link should take using the $before and $after args.
 *                                       Accepts 'link' (`<link>` tag), 'option' (`<option>` tag), 'html'
 *                                       (`<li>` tag), or a custom format, which generates a link anchor
 *                                       with $before preceding and $after succeeding. Default 'html'.
 *     @type string     $before          Markup to prepend to the beginning of each link. Default empty.
 *     @type string     $after           Markup to append to the end of each link. Default empty.
 *     @type bool       $show_post_count Whether to display the post count alongside the link. Default false.
 *     @type bool|int   $echo            Whether to echo or return the links list. Default 1|true to echo.
 *     @type string     $order           Whether to use ascending or descending order. Accepts 'ASC', or 'DESC'.
 *                                       Default 'DESC'.
 * }
 * @return string|void String when retrieving.
 */
function wp_get_archives($args = '')
{
    global $wpdb, $wp_locale;
    $defaults = array('type' => 'monthly', 'limit' => '', 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => false, 'echo' => 1, 'order' => 'DESC');
    $r = wp_parse_args($args, $defaults);
    if ('' == $r['type']) {
        $r['type'] = 'monthly';
    }
    if (!empty($r['limit'])) {
        $r['limit'] = absint($r['limit']);
        $r['limit'] = ' LIMIT ' . $r['limit'];
    }
    $order = strtoupper($r['order']);
    if ($order !== 'ASC') {
        $order = 'DESC';
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format = 'Y/m/d';
    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = get_option('date_format');
        $archive_week_start_date_format = get_option('date_format');
        $archive_week_end_date_format = get_option('date_format');
    }
    /**
     * Filter the SQL WHERE clause for retrieving archives.
     *
     * @since 2.2.0
     *
     * @param string $sql_where Portion of SQL query containing the WHERE clause.
     * @param array  $r         An array of default arguments.
     */
    $where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r);
    /**
     * Filter the SQL JOIN clause for retrieving archives.
     *
     * @since 2.2.0
     *
     * @param string $sql_join Portion of SQL query containing JOIN clause.
     * @param array  $r        An array of default arguments.
     */
    $join = apply_filters('getarchives_join', '', $r);
    $output = '';
    $last_changed = wp_cache_get('last_changed', 'posts');
    if (!$last_changed) {
        $last_changed = microtime();
        wp_cache_set('last_changed', $last_changed, 'posts');
    }
    $limit = $r['limit'];
    if ('monthly' == $r['type']) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                $url = get_month_link($result->year, $result->month);
                /* translators: 1: month name, 2: 4-digit year */
                $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($result->month), $result->year);
                if ($r['show_post_count']) {
                    $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                }
                $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
            }
        }
    } elseif ('yearly' == $r['type']) {
        $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date) ORDER BY post_date {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                $url = get_year_link($result->year);
                $text = sprintf('%d', $result->year);
                if ($r['show_post_count']) {
                    $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                }
                $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
            }
        }
    } elseif ('daily' == $r['type']) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                $url = get_day_link($result->year, $result->month, $result->dayofmonth);
                $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $result->year, $result->month, $result->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                if ($r['show_post_count']) {
                    $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                }
                $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
            }
        }
    } elseif ('weekly' == $r['type']) {
        $week = _wp_mysql_week('`post_date`');
        $query = "SELECT DISTINCT {$week} AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, count( `ID` ) AS `posts` FROM `{$wpdb->posts}` {$join} {$where} GROUP BY {$week}, YEAR( `post_date` ) ORDER BY `post_date` {$order} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        $arc_w_last = '';
        if ($results) {
            $after = $r['after'];
            foreach ((array) $results as $result) {
                if ($result->week != $arc_w_last) {
                    $arc_year = $result->yr;
                    $arc_w_last = $result->week;
                    $arc_week = get_weekstartend($result->yyyymmdd, get_option('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $result->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    if ($r['show_post_count']) {
                        $r['after'] = '&nbsp;(' . $result->posts . ')' . $after;
                    }
                    $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
                }
            }
        }
    } elseif ('postbypost' == $r['type'] || 'alpha' == $r['type']) {
        $orderby = 'alpha' == $r['type'] ? 'post_title ASC ' : 'post_date DESC, ID DESC ';
        $query = "SELECT * FROM {$wpdb->posts} {$join} {$where} ORDER BY {$orderby} {$limit}";
        $key = md5($query);
        $key = "wp_get_archives:{$key}:{$last_changed}";
        if (!($results = wp_cache_get($key, 'posts'))) {
            $results = $wpdb->get_results($query);
            wp_cache_set($key, $results, 'posts');
        }
        if ($results) {
            foreach ((array) $results as $result) {
                if ($result->post_date != '0000-00-00 00:00:00') {
                    $url = get_permalink($result);
                    if ($result->post_title) {
                        /** This filter is documented in wp-includes/post-template.php */
                        $text = strip_tags(apply_filters('the_title', $result->post_title, $result->ID));
                    } else {
                        $text = $result->ID;
                    }
                    $output .= get_archives_link($url, $text, $r['format'], $r['before'], $r['after']);
                }
            }
        }
    }
    if ($r['echo']) {
        echo $output;
    } else {
        return $output;
    }
}
Ejemplo n.º 2
0
 /**
  * @api
  * @param array|string $args
  * @return array|string
  */
 function get_items($args = null)
 {
     global $wpdb;
     $defaults = array('type' => 'monthly-nested', 'limit' => '', 'show_post_count' => false, 'order' => 'DESC', 'post_type' => 'post', 'show_year' => false, 'nested' => false);
     $args = wp_parse_args($args, $defaults);
     $post_type = $args['post_type'];
     $order = $args['order'];
     $nested = $args['nested'];
     $type = $args['type'];
     $limit = '';
     if ($type == 'yearlymonthly' || $type == 'yearmonth') {
         $type = 'monthly-nested';
     }
     if ($type == 'monthly-nested') {
         $nested = true;
     }
     if (!empty($args['limit'])) {
         $limit = absint($limit);
         $limit = ' LIMIT ' . $limit;
     }
     $order = strtoupper($order);
     if ($order !== 'ASC') {
         $order = 'DESC';
     }
     // this is what will separate dates on weekly archive links
     $archive_week_separator = '&#8211;';
     // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
     $archive_date_format_over_ride = 0;
     // options for daily archive (only if you over-ride the general date format)
     $archive_day_date_format = 'Y/m/d';
     // options for weekly archive (only if you over-ride the general date format)
     $archive_week_start_date_format = 'Y/m/d';
     $archive_week_end_date_format = 'Y/m/d';
     if (!$archive_date_format_over_ride) {
         $archive_day_date_format = get_option('date_format');
         $archive_week_start_date_format = get_option('date_format');
         $archive_week_end_date_format = get_option('date_format');
     }
     $where = $wpdb->prepare('WHERE post_type = "%s" AND post_status = "publish"', $post_type);
     $where = apply_filters('getarchives_where', $where, $args);
     $join = apply_filters('getarchives_join', '', $args);
     $output = array();
     $last_changed = wp_cache_get('last_changed', 'posts');
     if (!$last_changed) {
         $last_changed = microtime();
         wp_cache_set('last_changed', $last_changed, 'posts');
     }
     if ('monthly' == $type) {
         $output = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit, $nested);
     } elseif ('yearly' == $type) {
         $output = $this->get_items_yearly($args, $last_changed, $join, $where, $order, $limit);
     } elseif ('monthly-nested' == $type) {
         $years = $this->get_items_yearly($args, $last_changed, $join, $where, $order, $limit);
         foreach ($years as &$year) {
             $args = array('show_year' => false);
             $year['children'] = $this->get_items_monthly($args, $last_changed, $join, $where, $order, $limit);
         }
         $output = $years;
     } elseif ('daily' == $type) {
         $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date {$order} {$limit}";
         $key = md5($query);
         $key = "wp_get_archives:{$key}:{$last_changed}";
         if (!($results = wp_cache_get($key, 'posts'))) {
             $results = $wpdb->get_results($query);
             $cache = array();
             $cache[$key] = $results;
             wp_cache_set($key, $results, 'posts');
         }
         if ($results) {
             foreach ((array) $results as $result) {
                 $url = get_day_link($result->year, $result->month, $result->dayofmonth);
                 $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $result->year, $result->month, $result->dayofmonth);
                 $text = mysql2date($archive_day_date_format, $date);
                 $output[] = $this->get_archives_link($url, $text);
             }
         }
     } elseif ('weekly' == $type) {
         $week = _wp_mysql_week('`post_date`');
         $query = "SELECT DISTINCT {$week} AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, " . "count( `ID` ) AS `posts` FROM `{$wpdb->posts}` {$join} {$where} GROUP BY {$week}, YEAR( `post_date` ) ORDER BY `post_date` {$order} {$limit}";
         $key = md5($query);
         $key = "wp_get_archives:{$key}:{$last_changed}";
         if (!($results = wp_cache_get($key, 'posts'))) {
             $results = $wpdb->get_results($query);
             wp_cache_set($key, $results, 'posts');
         }
         $arc_w_last = '';
         if ($results) {
             foreach ((array) $results as $result) {
                 if ($result->week != $arc_w_last) {
                     $arc_year = $result->yr;
                     $arc_w_last = $result->week;
                     $arc_week = get_weekstartend($result->yyyymmdd, get_option('start_of_week'));
                     $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                     $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                     $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $result->week);
                     $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                     $output[] = $this->get_archives_link($url, $text);
                 }
             }
         }
     } elseif ('postbypost' == $type || 'alpha' == $type) {
         $orderby = 'alpha' == $type ? 'post_title ASC ' : 'post_date DESC ';
         $query = "SELECT * FROM {$wpdb->posts} {$join} {$where} ORDER BY {$orderby} {$limit}";
         $key = md5($query);
         $key = "wp_get_archives:{$key}:{$last_changed}";
         if (!($results = wp_cache_get($key, 'posts'))) {
             $results = $wpdb->get_results($query);
             wp_cache_set($key, $results, 'posts');
         }
         if ($results) {
             foreach ((array) $results as $result) {
                 if ($result->post_date != '0000-00-00 00:00:00') {
                     $url = get_permalink($result);
                     if ($result->post_title) {
                         /** This filter is documented in wp-includes/post-template.php */
                         $text = strip_tags(apply_filters('the_title', $result->post_title, $result->ID));
                     } else {
                         $text = $result->ID;
                     }
                     $output[] = $this->get_archives_link($url, $text);
                 }
             }
         }
     }
     return $output;
 }
Ejemplo n.º 3
0
/**
 * Display archive links based on type and format.
 *
 * The 'type' argument offers a few choices and by default will display monthly
 * archive links. The other options for values are 'daily', 'weekly', 'monthly',
 * 'yearly', 'postbypost' or 'alpha'. Both 'postbypost' and 'alpha' display the
 * same archive link list, the difference between the two is that 'alpha'
 * will order by post title and 'postbypost' will order by post date.
 *
 * The date archives will logically display dates with links to the archive post
 * page. The 'postbypost' and 'alpha' values for 'type' argument will display
 * the post titles.
 *
 * The 'limit' argument will only display a limited amount of links, specified
 * by the 'limit' integer value. By default, there is no limit. The
 * 'show_post_count' argument will show how many posts are within the archive.
 * By default, the 'show_post_count' argument is set to false.
 *
 * For the 'format', 'before', and 'after' arguments, see {@link
 * get_archives_link()}. The values of these arguments have to do with that
 * function.
 *
 * @since 1.2.0
 *
 * @param string|array $args Optional. Override defaults.
 */
function wp_get_archives($args = '')
{
    global $wpdb, $wp_locale;
    $defaults = array('type' => 'monthly', 'limit' => '', 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => false, 'echo' => 1);
    $r = wp_parse_args($args, $defaults);
    extract($r, EXTR_SKIP);
    if ('' == $type) {
        $type = 'monthly';
    }
    if ('' != $limit) {
        $limit = absint($limit);
        $limit = ' LIMIT ' . $limit;
    }
    // this is what will separate dates on weekly archive links
    $archive_week_separator = '&#8211;';
    // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride
    $archive_date_format_over_ride = 0;
    // options for daily archive (only if you over-ride the general date format)
    $archive_day_date_format = 'Y/m/d';
    // options for weekly archive (only if you over-ride the general date format)
    $archive_week_start_date_format = 'Y/m/d';
    $archive_week_end_date_format = 'Y/m/d';
    if (!$archive_date_format_over_ride) {
        $archive_day_date_format = get_option('date_format');
        $archive_week_start_date_format = get_option('date_format');
        $archive_week_end_date_format = get_option('date_format');
    }
    //filters
    $where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r);
    $join = apply_filters('getarchives_join', '', $r);
    $output = '';
    if ('monthly' == $type) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            $afterafter = $after;
            foreach ((array) $arcresults as $arcresult) {
                $url = get_month_link($arcresult->year, $arcresult->month);
                /* translators: 1: month name, 2: 4-digit year */
                $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                $output .= get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('yearly' == $type) {
        $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date) ORDER BY post_date DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            $afterafter = $after;
            foreach ((array) $arcresults as $arcresult) {
                $url = get_year_link($arcresult->year);
                $text = sprintf('%d', $arcresult->year);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                $output .= get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('daily' == $type) {
        $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM {$wpdb->posts} {$join} {$where} GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            $afterafter = $after;
            foreach ((array) $arcresults as $arcresult) {
                $url = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $arcresult->year, $arcresult->month, $arcresult->dayofmonth);
                $text = mysql2date($archive_day_date_format, $date);
                if ($show_post_count) {
                    $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                }
                $output .= get_archives_link($url, $text, $format, $before, $after);
            }
        }
    } elseif ('weekly' == $type) {
        $week = _wp_mysql_week('`post_date`');
        $query = "SELECT DISTINCT {$week} AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, count( `ID` ) AS `posts` FROM `{$wpdb->posts}` {$join} {$where} GROUP BY {$week}, YEAR( `post_date` ) ORDER BY `post_date` DESC {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        $arc_w_last = '';
        $afterafter = $after;
        if ($arcresults) {
            foreach ((array) $arcresults as $arcresult) {
                if ($arcresult->week != $arc_w_last) {
                    $arc_year = $arcresult->yr;
                    $arc_w_last = $arcresult->week;
                    $arc_week = get_weekstartend($arcresult->yyyymmdd, get_option('start_of_week'));
                    $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']);
                    $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']);
                    $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $arcresult->week);
                    $text = $arc_week_start . $archive_week_separator . $arc_week_end;
                    if ($show_post_count) {
                        $after = '&nbsp;(' . $arcresult->posts . ')' . $afterafter;
                    }
                    $output .= get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    } elseif ('postbypost' == $type || 'alpha' == $type) {
        $orderby = 'alpha' == $type ? 'post_title ASC ' : 'post_date DESC ';
        $query = "SELECT * FROM {$wpdb->posts} {$join} {$where} ORDER BY {$orderby} {$limit}";
        $key = md5($query);
        $cache = wp_cache_get('wp_get_archives', 'general');
        if (!isset($cache[$key])) {
            $arcresults = $wpdb->get_results($query);
            $cache[$key] = $arcresults;
            wp_cache_set('wp_get_archives', $cache, 'general');
        } else {
            $arcresults = $cache[$key];
        }
        if ($arcresults) {
            foreach ((array) $arcresults as $arcresult) {
                if ($arcresult->post_date != '0000-00-00 00:00:00') {
                    $url = get_permalink($arcresult);
                    if ($arcresult->post_title) {
                        $text = strip_tags(apply_filters('the_title', $arcresult->post_title, $arcresult->ID));
                    } else {
                        $text = $arcresult->ID;
                    }
                    $output .= get_archives_link($url, $text, $format, $before, $after);
                }
            }
        }
    }
    if ($echo) {
        echo $output;
    } else {
        return $output;
    }
}
Ejemplo n.º 4
0
 /**
  * Retrieve the posts based on query variables.
  *
  * There are a few filters and actions that can be used to modify the post
  * database query.
  *
  * @since 1.5.0
  * @access public
  * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts.
  *
  * @return array List of posts.
  */
 function &get_posts()
 {
     global $wpdb, $user_ID, $_wp_using_ext_object_cache;
     $this->parse_query();
     do_action_ref_array('pre_get_posts', array(&$this));
     // Shorthand.
     $q =& $this->query_vars;
     // Fill again in case pre_get_posts unset some vars.
     $q = $this->fill_query_vars($q);
     // Parse meta query
     $this->meta_query = new WP_Meta_Query();
     $this->meta_query->parse_query_vars($q);
     // Set a flag if a pre_get_posts hook changed the query vars.
     $hash = md5(serialize($this->query_vars));
     if ($hash != $this->query_vars_hash) {
         $this->query_vars_changed = true;
         $this->query_vars_hash = $hash;
     }
     unset($hash);
     // First let's clear some variables
     $distinct = '';
     $whichauthor = '';
     $whichmimetype = '';
     $where = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     $fields = '';
     $post_status_join = false;
     $page = 1;
     if (isset($q['caller_get_posts'])) {
         _deprecated_argument('WP_Query', '3.1', __('"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.'));
         if (!isset($q['ignore_sticky_posts'])) {
             $q['ignore_sticky_posts'] = $q['caller_get_posts'];
         }
     }
     if (!isset($q['ignore_sticky_posts'])) {
         $q['ignore_sticky_posts'] = false;
     }
     if (!isset($q['suppress_filters'])) {
         $q['suppress_filters'] = false;
     }
     if (!isset($q['cache_results'])) {
         if ($_wp_using_ext_object_cache) {
             $q['cache_results'] = false;
         } else {
             $q['cache_results'] = true;
         }
     }
     if (!isset($q['update_post_term_cache'])) {
         $q['update_post_term_cache'] = true;
     }
     if (!isset($q['update_post_meta_cache'])) {
         $q['update_post_meta_cache'] = true;
     }
     if (!isset($q['post_type'])) {
         if ($this->is_search) {
             $q['post_type'] = 'any';
         } else {
             $q['post_type'] = '';
         }
     }
     $post_type = $q['post_type'];
     if (!isset($q['posts_per_page']) || $q['posts_per_page'] == 0) {
         $q['posts_per_page'] = get_option('posts_per_page');
     }
     if (isset($q['showposts']) && $q['showposts']) {
         $q['showposts'] = (int) $q['showposts'];
         $q['posts_per_page'] = $q['showposts'];
     }
     if (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0 && ($this->is_archive || $this->is_search)) {
         $q['posts_per_page'] = $q['posts_per_archive_page'];
     }
     if (!isset($q['nopaging'])) {
         if ($q['posts_per_page'] == -1) {
             $q['nopaging'] = true;
         } else {
             $q['nopaging'] = false;
         }
     }
     if ($this->is_feed) {
         $q['posts_per_page'] = get_option('posts_per_rss');
         $q['nopaging'] = false;
     }
     $q['posts_per_page'] = (int) $q['posts_per_page'];
     if ($q['posts_per_page'] < -1) {
         $q['posts_per_page'] = abs($q['posts_per_page']);
     } else {
         if ($q['posts_per_page'] == 0) {
             $q['posts_per_page'] = 1;
         }
     }
     if (!isset($q['comments_per_page']) || $q['comments_per_page'] == 0) {
         $q['comments_per_page'] = get_option('comments_per_page');
     }
     if ($this->is_home && (empty($this->query) || $q['preview'] == 'true') && 'page' == get_option('show_on_front') && get_option('page_on_front')) {
         $this->is_page = true;
         $this->is_home = false;
         $q['page_id'] = get_option('page_on_front');
     }
     if (isset($q['page'])) {
         $q['page'] = trim($q['page'], '/');
         $q['page'] = absint($q['page']);
     }
     // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
     if (isset($q['no_found_rows'])) {
         $q['no_found_rows'] = (bool) $q['no_found_rows'];
     } else {
         $q['no_found_rows'] = false;
     }
     switch ($q['fields']) {
         case 'ids':
             $fields = "{$wpdb->posts}.ID";
             break;
         case 'id=>parent':
             $fields = "{$wpdb->posts}.ID, {$wpdb->posts}.post_parent";
             break;
         default:
             $fields = "{$wpdb->posts}.*";
     }
     // If a month is specified in the querystring, load that month
     if ($q['m']) {
         $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
         $where .= " AND YEAR({$wpdb->posts}.post_date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$wpdb->posts}.post_date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$wpdb->posts}.post_date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$wpdb->posts}.post_date)=" . substr($q['m'], 12, 2);
         }
     }
     if ('' !== $q['hour']) {
         $where .= " AND HOUR({$wpdb->posts}.post_date)='" . $q['hour'] . "'";
     }
     if ('' !== $q['minute']) {
         $where .= " AND MINUTE({$wpdb->posts}.post_date)='" . $q['minute'] . "'";
     }
     if ('' !== $q['second']) {
         $where .= " AND SECOND({$wpdb->posts}.post_date)='" . $q['second'] . "'";
     }
     if ($q['year']) {
         $where .= " AND YEAR({$wpdb->posts}.post_date)='" . $q['year'] . "'";
     }
     if ($q['monthnum']) {
         $where .= " AND MONTH({$wpdb->posts}.post_date)='" . $q['monthnum'] . "'";
     }
     if ($q['day']) {
         $where .= " AND DAYOFMONTH({$wpdb->posts}.post_date)='" . $q['day'] . "'";
     }
     // If we've got a post_type AND its not "any" post_type.
     if (!empty($q['post_type']) && 'any' != $q['post_type']) {
         foreach ((array) $q['post_type'] as $_post_type) {
             $ptype_obj = get_post_type_object($_post_type);
             if (!$ptype_obj || !$ptype_obj->query_var || empty($q[$ptype_obj->query_var])) {
                 continue;
             }
             if (!$ptype_obj->hierarchical || strpos($q[$ptype_obj->query_var], '/') === false) {
                 // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name'
                 $q['name'] = $q[$ptype_obj->query_var];
             } else {
                 // Hierarchical post_types will operate through the
                 $q['pagename'] = $q[$ptype_obj->query_var];
                 $q['name'] = '';
             }
             // Only one request for a slug is possible, this is why name & pagename are overwritten above.
             break;
         }
         //end foreach
         unset($ptype_obj);
     }
     if ('' != $q['name']) {
         $q['name'] = sanitize_title_for_query($q['name']);
         $where .= " AND {$wpdb->posts}.post_name = '" . $q['name'] . "'";
     } elseif ('' != $q['pagename']) {
         if (isset($this->queried_object_id)) {
             $reqpage = $this->queried_object_id;
         } else {
             if ('page' != $q['post_type']) {
                 foreach ((array) $q['post_type'] as $_post_type) {
                     $ptype_obj = get_post_type_object($_post_type);
                     if (!$ptype_obj || !$ptype_obj->hierarchical) {
                         continue;
                     }
                     $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type);
                     if ($reqpage) {
                         break;
                     }
                 }
                 unset($ptype_obj);
             } else {
                 $reqpage = get_page_by_path($q['pagename']);
             }
             if (!empty($reqpage)) {
                 $reqpage = $reqpage->ID;
             } else {
                 $reqpage = 0;
             }
         }
         $page_for_posts = get_option('page_for_posts');
         if ('page' != get_option('show_on_front') || empty($page_for_posts) || $reqpage != $page_for_posts) {
             $q['pagename'] = sanitize_title_for_query(wp_basename($q['pagename']));
             $q['name'] = $q['pagename'];
             $where .= " AND ({$wpdb->posts}.ID = '{$reqpage}')";
             $reqpage_obj = get_page($reqpage);
             if (is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type) {
                 $this->is_attachment = true;
                 $post_type = $q['post_type'] = 'attachment';
                 $this->is_page = true;
                 $q['attachment_id'] = $reqpage;
             }
         }
     } elseif ('' != $q['attachment']) {
         $q['attachment'] = sanitize_title_for_query(wp_basename($q['attachment']));
         $q['name'] = $q['attachment'];
         $where .= " AND {$wpdb->posts}.post_name = '" . $q['attachment'] . "'";
     }
     if ($q['w']) {
         $where .= ' AND ' . _wp_mysql_week("`{$wpdb->posts}`.`post_date`") . " = '" . $q['w'] . "'";
     }
     if (intval($q['comments_popup'])) {
         $q['p'] = absint($q['comments_popup']);
     }
     // If an attachment is requested by number, let it supersede any post number.
     if ($q['attachment_id']) {
         $q['p'] = absint($q['attachment_id']);
     }
     // If a post number is specified, load that post
     if ($q['p']) {
         $where .= " AND {$wpdb->posts}.ID = " . $q['p'];
     } elseif ($q['post__in']) {
         $post__in = implode(',', array_map('absint', $q['post__in']));
         $where .= " AND {$wpdb->posts}.ID IN ({$post__in})";
     } elseif ($q['post__not_in']) {
         $post__not_in = implode(',', array_map('absint', $q['post__not_in']));
         $where .= " AND {$wpdb->posts}.ID NOT IN ({$post__not_in})";
     }
     if (is_numeric($q['post_parent'])) {
         $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_parent = %d ", $q['post_parent']);
     }
     if ($q['page_id']) {
         if ('page' != get_option('show_on_front') || $q['page_id'] != get_option('page_for_posts')) {
             $q['p'] = $q['page_id'];
             $where = " AND {$wpdb->posts}.ID = " . $q['page_id'];
         }
     }
     // If a search pattern is specified, load the posts that match
     if (!empty($q['s'])) {
         // added slashes screw with quote grouping when done early, so done later
         $q['s'] = stripslashes($q['s']);
         if (!empty($q['sentence'])) {
             $q['search_terms'] = array($q['s']);
         } else {
             preg_match_all('/".*?("|$)|((?<=[\\r\\n\\t ",+])|^)[^\\r\\n\\t ",+]+/', $q['s'], $matches);
             $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]);
         }
         $n = !empty($q['exact']) ? '' : '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = esc_sql(like_escape($term));
             $search .= "{$searchand}(({$wpdb->posts}.post_title LIKE '{$n}{$term}{$n}') OR ({$wpdb->posts}.post_content LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
             if (!is_user_logged_in()) {
                 $search .= " AND ({$wpdb->posts}.post_password = '') ";
             }
         }
     }
     // Allow plugins to contextually add/remove/modify the search section of the database query
     $search = apply_filters_ref_array('posts_search', array($search, &$this));
     // Taxonomies
     if (!$this->is_singular) {
         $this->parse_tax_query($q);
         $clauses = $this->tax_query->get_sql($wpdb->posts, 'ID');
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     if ($this->is_tax) {
         if (empty($post_type)) {
             $post_type = 'any';
             $post_status_join = true;
         } elseif (in_array('attachment', (array) $post_type)) {
             $post_status_join = true;
         }
     }
     // Back-compat
     if (!empty($this->tax_query->queries)) {
         $tax_query_in_and = wp_list_filter($this->tax_query->queries, array('operator' => 'NOT IN'), 'NOT');
         if (!empty($tax_query_in_and)) {
             if (!isset($q['taxonomy'])) {
                 foreach ($tax_query_in_and as $a_tax_query) {
                     if (!in_array($a_tax_query['taxonomy'], array('category', 'post_tag'))) {
                         $q['taxonomy'] = $a_tax_query['taxonomy'];
                         if ('slug' == $a_tax_query['field']) {
                             $q['term'] = $a_tax_query['terms'][0];
                         } else {
                             $q['term_id'] = $a_tax_query['terms'][0];
                         }
                         break;
                     }
                 }
             }
             $cat_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'category'));
             if (!empty($cat_query)) {
                 $cat_query = reset($cat_query);
                 $the_cat = get_term_by($cat_query['field'], $cat_query['terms'][0], 'category');
                 if ($the_cat) {
                     $this->set('cat', $the_cat->term_id);
                     $this->set('category_name', $the_cat->slug);
                 }
                 unset($the_cat);
             }
             unset($cat_query);
             $tag_query = wp_list_filter($tax_query_in_and, array('taxonomy' => 'post_tag'));
             if (!empty($tag_query)) {
                 $tag_query = reset($tag_query);
                 $the_tag = get_term_by($tag_query['field'], $tag_query['terms'][0], 'post_tag');
                 if ($the_tag) {
                     $this->set('tag_id', $the_tag->term_id);
                 }
                 unset($the_tag);
             }
             unset($tag_query);
         }
     }
     if (!empty($this->tax_query->queries) || !empty($this->meta_query->queries)) {
         $groupby = "{$wpdb->posts}.ID";
     }
     // Author/user stuff
     if (empty($q['author']) || $q['author'] == '0') {
         $whichauthor = '';
     } else {
         $q['author'] = (string) urldecode($q['author']);
         $q['author'] = addslashes_gpc($q['author']);
         if (strpos($q['author'], '-') !== false) {
             $eq = '!=';
             $andor = 'AND';
             $q['author'] = explode('-', $q['author']);
             $q['author'] = (string) absint($q['author'][1]);
         } else {
             $eq = '=';
             $andor = 'OR';
         }
         $author_array = preg_split('/[,\\s]+/', $q['author']);
         $_author_array = array();
         foreach ($author_array as $key => $_author) {
             $_author_array[] = "{$wpdb->posts}.post_author " . $eq . ' ' . absint($_author);
         }
         $whichauthor .= ' AND (' . implode(" {$andor} ", $_author_array) . ')';
         unset($author_array, $_author_array);
     }
     // Author stuff for nice URLs
     if ('' != $q['author_name']) {
         if (strpos($q['author_name'], '/') !== false) {
             $q['author_name'] = explode('/', $q['author_name']);
             if ($q['author_name'][count($q['author_name']) - 1]) {
                 $q['author_name'] = $q['author_name'][count($q['author_name']) - 1];
                 // no trailing slash
             } else {
                 $q['author_name'] = $q['author_name'][count($q['author_name']) - 2];
                 // there was a trailing slash
             }
         }
         $q['author_name'] = sanitize_title_for_query($q['author_name']);
         $q['author'] = get_user_by('slug', $q['author_name']);
         if ($q['author']) {
             $q['author'] = $q['author']->ID;
         }
         $whichauthor .= " AND ({$wpdb->posts}.post_author = " . absint($q['author']) . ')';
     }
     // MIME-Type stuff for attachment browsing
     if (isset($q['post_mime_type']) && '' != $q['post_mime_type']) {
         $whichmimetype = wp_post_mime_type_where($q['post_mime_type'], $wpdb->posts);
     }
     $where .= $search . $whichauthor . $whichmimetype;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby'])) {
         $orderby = "{$wpdb->posts}.post_date " . $q['order'];
     } elseif ('none' == $q['orderby']) {
         $orderby = '';
     } else {
         // Used to filter values
         $allowed_keys = array('name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count');
         if (!empty($q['meta_key'])) {
             $allowed_keys[] = $q['meta_key'];
             $allowed_keys[] = 'meta_value';
             $allowed_keys[] = 'meta_value_num';
         }
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = array();
         foreach (explode(' ', $q['orderby']) as $i => $orderby) {
             // Only allow certain values for safety
             if (!in_array($orderby, $allowed_keys)) {
                 continue;
             }
             switch ($orderby) {
                 case 'menu_order':
                     break;
                 case 'ID':
                     $orderby = "{$wpdb->posts}.ID";
                     break;
                 case 'rand':
                     $orderby = 'RAND()';
                     break;
                 case $q['meta_key']:
                 case 'meta_value':
                     $orderby = "{$wpdb->postmeta}.meta_value";
                     break;
                 case 'meta_value_num':
                     $orderby = "{$wpdb->postmeta}.meta_value+0";
                     break;
                 case 'comment_count':
                     $orderby = "{$wpdb->posts}.comment_count";
                     break;
                 default:
                     $orderby = "{$wpdb->posts}.post_" . $orderby;
             }
             $orderby_array[] = $orderby;
         }
         $orderby = implode(',', $orderby_array);
         if (empty($orderby)) {
             $orderby = "{$wpdb->posts}.post_date " . $q['order'];
         } else {
             $orderby .= " {$q['order']}";
         }
     }
     if (is_array($post_type)) {
         $post_type_cap = 'multiple_post_type';
     } else {
         $post_type_object = get_post_type_object($post_type);
         if (empty($post_type_object)) {
             $post_type_cap = $post_type;
         }
     }
     if ('any' == $post_type) {
         $in_search_post_types = get_post_types(array('exclude_from_search' => false));
         if (!empty($in_search_post_types)) {
             $where .= $wpdb->prepare(" AND {$wpdb->posts}.post_type IN ('" . join("', '", $in_search_post_types) . "')");
         }
     } elseif (!empty($post_type) && is_array($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type IN ('" . join("', '", $post_type) . "')";
     } elseif (!empty($post_type)) {
         $where .= " AND {$wpdb->posts}.post_type = '{$post_type}'";
         $post_type_object = get_post_type_object($post_type);
     } elseif ($this->is_attachment) {
         $where .= " AND {$wpdb->posts}.post_type = 'attachment'";
         $post_type_object = get_post_type_object('attachment');
     } elseif ($this->is_page) {
         $where .= " AND {$wpdb->posts}.post_type = 'page'";
         $post_type_object = get_post_type_object('page');
     } else {
         $where .= " AND {$wpdb->posts}.post_type = 'post'";
         $post_type_object = get_post_type_object('post');
     }
     if (!empty($post_type_object)) {
         $edit_cap = $post_type_object->cap->edit_post;
         $read_cap = $post_type_object->cap->read_post;
         $edit_others_cap = $post_type_object->cap->edit_others_posts;
         $read_private_cap = $post_type_object->cap->read_private_posts;
     } else {
         $edit_cap = 'edit_' . $post_type_cap;
         $read_cap = 'read_' . $post_type_cap;
         $edit_others_cap = 'edit_others_' . $post_type_cap . 's';
         $read_private_cap = 'read_private_' . $post_type_cap . 's';
     }
     if (!empty($q['post_status'])) {
         $statuswheres = array();
         $q_status = $q['post_status'];
         if (!is_array($q_status)) {
             $q_status = explode(',', $q_status);
         }
         $r_status = array();
         $p_status = array();
         $e_status = array();
         if (in_array('any', $q_status)) {
             foreach (get_post_stati(array('exclude_from_search' => true)) as $status) {
                 $e_status[] = "{$wpdb->posts}.post_status <> '{$status}'";
             }
         } else {
             foreach (get_post_stati() as $status) {
                 if (in_array($status, $q_status)) {
                     if ('private' == $status) {
                         $p_status[] = "{$wpdb->posts}.post_status = '{$status}'";
                     } else {
                         $r_status[] = "{$wpdb->posts}.post_status = '{$status}'";
                     }
                 }
             }
         }
         if (empty($q['perm']) || 'readable' != $q['perm']) {
             $r_status = array_merge($r_status, $p_status);
             unset($p_status);
         }
         if (!empty($e_status)) {
             $statuswheres[] = "(" . join(' AND ', $e_status) . ")";
         }
         if (!empty($r_status)) {
             if (!empty($q['perm']) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap)) {
                 $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $r_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $r_status) . ")";
             }
         }
         if (!empty($p_status)) {
             if (!empty($q['perm']) && 'readable' == $q['perm'] && !current_user_can($read_private_cap)) {
                 $statuswheres[] = "({$wpdb->posts}.post_author = {$user_ID} " . "AND (" . join(' OR ', $p_status) . "))";
             } else {
                 $statuswheres[] = "(" . join(' OR ', $p_status) . ")";
             }
         }
         if ($post_status_join) {
             $join .= " LEFT JOIN {$wpdb->posts} AS p2 ON ({$wpdb->posts}.post_parent = p2.ID) ";
             foreach ($statuswheres as $index => $statuswhere) {
                 $statuswheres[$index] = "({$statuswhere} OR ({$wpdb->posts}.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))";
             }
         }
         foreach ($statuswheres as $statuswhere) {
             $where .= " AND {$statuswhere}";
         }
     } elseif (!$this->is_singular) {
         $where .= " AND ({$wpdb->posts}.post_status = 'publish'";
         // Add public states.
         $public_states = get_post_stati(array('public' => true));
         foreach ((array) $public_states as $state) {
             if ('publish' == $state) {
                 // Publish is hard-coded above.
                 continue;
             }
             $where .= " OR {$wpdb->posts}.post_status = '{$state}'";
         }
         if ($this->is_admin) {
             // Add protected states that should show in the admin all list.
             $admin_all_states = get_post_stati(array('protected' => true, 'show_in_admin_all_list' => true));
             foreach ((array) $admin_all_states as $state) {
                 $where .= " OR {$wpdb->posts}.post_status = '{$state}'";
             }
         }
         if (is_user_logged_in()) {
             // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states.
             $private_states = get_post_stati(array('private' => true));
             foreach ((array) $private_states as $state) {
                 $where .= current_user_can($read_private_cap) ? " OR {$wpdb->posts}.post_status = '{$state}'" : " OR {$wpdb->posts}.post_author = {$user_ID} AND {$wpdb->posts}.post_status = '{$state}'";
             }
         }
         $where .= ')';
     }
     if (!empty($this->meta_query->queries)) {
         $clauses = $this->meta_query->get_sql('post', $wpdb->posts, 'ID', $this);
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     // Apply filters on where and join prior to paging so that any
     // manipulations to them are reflected in the paging by day queries.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where', array($where, &$this));
         $join = apply_filters_ref_array('posts_join', array($join, &$this));
     }
     // Paging
     if (empty($q['nopaging']) && !$this->is_singular) {
         $page = absint($q['paged']);
         if (!$page) {
             $page = 1;
         }
         if (empty($q['offset'])) {
             $pgstrt = ($page - 1) * $q['posts_per_page'] . ', ';
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
         }
         $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
     }
     // Comments feeds
     if ($this->is_comment_feed && ($this->is_archive || $this->is_search || !$this->is_singular)) {
         if ($this->is_archive || $this->is_search) {
             $cjoin = "JOIN {$wpdb->posts} ON ({$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID) {$join} ";
             $cwhere = "WHERE comment_approved = '1' {$where}";
             $cgroupby = "{$wpdb->comments}.comment_id";
         } else {
             // Other non singular e.g. front
             $cjoin = "JOIN {$wpdb->posts} ON ( {$wpdb->comments}.comment_post_ID = {$wpdb->posts}.ID )";
             $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
             $cgroupby = '';
         }
         if (!$q['suppress_filters']) {
             $cjoin = apply_filters_ref_array('comment_feed_join', array($cjoin, &$this));
             $cwhere = apply_filters_ref_array('comment_feed_where', array($cwhere, &$this));
             $cgroupby = apply_filters_ref_array('comment_feed_groupby', array($cgroupby, &$this));
             $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
             $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this));
         }
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $this->comments = (array) $wpdb->get_results("SELECT {$distinct} {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}");
         $this->comment_count = count($this->comments);
         $post_ids = array();
         foreach ($this->comments as $comment) {
             $post_ids[] = (int) $comment->comment_post_ID;
         }
         $post_ids = join(',', $post_ids);
         $join = '';
         if ($post_ids) {
             $where = "AND {$wpdb->posts}.ID IN ({$post_ids}) ";
         } else {
             $where = "AND 0";
         }
     }
     $pieces = array('where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits');
     // Apply post-paging filters on where and join. Only plugins that
     // manipulate paging queries should use these hooks.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_paged', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_paged', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct', array($distinct, &$this));
         $limits = apply_filters_ref_array('post_limits', array($limits, &$this));
         $fields = apply_filters_ref_array('posts_fields', array($fields, &$this));
         // Filter all clauses at once, for convenience
         $clauses = (array) apply_filters_ref_array('posts_clauses', array(compact($pieces), &$this));
         foreach ($pieces as $piece) {
             ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : '';
         }
     }
     // Announce current selection parameters. For use by caching plugins.
     do_action('posts_selection', $where . $groupby . $orderby . $limits . $join);
     // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above.
     if (!$q['suppress_filters']) {
         $where = apply_filters_ref_array('posts_where_request', array($where, &$this));
         $groupby = apply_filters_ref_array('posts_groupby_request', array($groupby, &$this));
         $join = apply_filters_ref_array('posts_join_request', array($join, &$this));
         $orderby = apply_filters_ref_array('posts_orderby_request', array($orderby, &$this));
         $distinct = apply_filters_ref_array('posts_distinct_request', array($distinct, &$this));
         $fields = apply_filters_ref_array('posts_fields_request', array($fields, &$this));
         $limits = apply_filters_ref_array('post_limits_request', array($limits, &$this));
         // Filter all clauses at once, for convenience
         $clauses = (array) apply_filters_ref_array('posts_clauses_request', array(compact($pieces), &$this));
         foreach ($pieces as $piece) {
             ${$piece} = isset($clauses[$piece]) ? $clauses[$piece] : '';
         }
     }
     if (!empty($groupby)) {
         $groupby = 'GROUP BY ' . $groupby;
     }
     if (!empty($orderby)) {
         $orderby = 'ORDER BY ' . $orderby;
     }
     $found_rows = '';
     if (!$q['no_found_rows'] && !empty($limits)) {
         $found_rows = 'SQL_CALC_FOUND_ROWS';
     }
     $this->request = $old_request = "SELECT {$found_rows} {$distinct} {$fields} FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
     if (!$q['suppress_filters']) {
         $this->request = apply_filters_ref_array('posts_request', array($this->request, &$this));
     }
     if ('ids' == $q['fields']) {
         $this->posts = $wpdb->get_col($this->request);
         return $this->posts;
     }
     if ('id=>parent' == $q['fields']) {
         $this->posts = $wpdb->get_results($this->request);
         $r = array();
         foreach ($this->posts as $post) {
             $r[$post->ID] = $post->post_parent;
         }
         return $r;
     }
     if ($old_request == $this->request && "{$wpdb->posts}.*" == $fields) {
         // First get the IDs and then fill in the objects
         $this->request = "SELECT {$found_rows} {$distinct} {$wpdb->posts}.ID FROM {$wpdb->posts} {$join} WHERE 1=1 {$where} {$groupby} {$orderby} {$limits}";
         $this->request = apply_filters('posts_request_ids', $this->request, $this);
         $ids = $wpdb->get_col($this->request);
         if ($ids) {
             $this->set_found_posts($q, $limits);
             _prime_post_caches($ids, $q['update_post_term_cache'], $q['update_post_meta_cache']);
             $this->posts = array_map('get_post', $ids);
         } else {
             $this->found_posts = $this->max_num_pages = 0;
             $this->posts = array();
         }
     } else {
         $this->posts = $wpdb->get_results($this->request);
         $this->set_found_posts($q, $limits);
     }
     // Raw results filter. Prior to status checks.
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('posts_results', array($this->posts, &$this));
     }
     if (!empty($this->posts) && $this->is_comment_feed && $this->is_singular) {
         $cjoin = apply_filters_ref_array('comment_feed_join', array('', &$this));
         $cwhere = apply_filters_ref_array('comment_feed_where', array("WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this));
         $cgroupby = apply_filters_ref_array('comment_feed_groupby', array('', &$this));
         $cgroupby = !empty($cgroupby) ? 'GROUP BY ' . $cgroupby : '';
         $corderby = apply_filters_ref_array('comment_feed_orderby', array('comment_date_gmt DESC', &$this));
         $corderby = !empty($corderby) ? 'ORDER BY ' . $corderby : '';
         $climits = apply_filters_ref_array('comment_feed_limits', array('LIMIT ' . get_option('posts_per_rss'), &$this));
         $comments_request = "SELECT {$wpdb->comments}.* FROM {$wpdb->comments} {$cjoin} {$cwhere} {$cgroupby} {$corderby} {$climits}";
         $this->comments = $wpdb->get_results($comments_request);
         $this->comment_count = count($this->comments);
     }
     // Check post status to determine if post should be displayed.
     if (!empty($this->posts) && ($this->is_single || $this->is_page)) {
         $status = get_post_status($this->posts[0]->ID);
         $post_status_obj = get_post_status_object($status);
         //$type = get_post_type($this->posts[0]);
         if (!$post_status_obj->public) {
             if (!is_user_logged_in()) {
                 // User must be logged in to view unpublished posts.
                 $this->posts = array();
             } else {
                 if ($post_status_obj->protected) {
                     // User must have edit permissions on the draft to preview.
                     if (!current_user_can($edit_cap, $this->posts[0]->ID)) {
                         $this->posts = array();
                     } else {
                         $this->is_preview = true;
                         if ('future' != $status) {
                             $this->posts[0]->post_date = current_time('mysql');
                         }
                     }
                 } elseif ($post_status_obj->private) {
                     if (!current_user_can($read_cap, $this->posts[0]->ID)) {
                         $this->posts = array();
                     }
                 } else {
                     $this->posts = array();
                 }
             }
         }
         if ($this->is_preview && $this->posts && current_user_can($edit_cap, $this->posts[0]->ID)) {
             $this->posts[0] = apply_filters_ref_array('the_preview', array($this->posts[0], &$this));
         }
     }
     // Put sticky posts at the top of the posts array
     $sticky_posts = get_option('sticky_posts');
     if ($this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts']) {
         $num_posts = count($this->posts);
         $sticky_offset = 0;
         // Loop over posts and relocate stickies to the front.
         for ($i = 0; $i < $num_posts; $i++) {
             if (in_array($this->posts[$i]->ID, $sticky_posts)) {
                 $sticky_post = $this->posts[$i];
                 // Remove sticky from current position
                 array_splice($this->posts, $i, 1);
                 // Move to front, after other stickies
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 // Increment the sticky offset. The next sticky will be placed at this offset.
                 $sticky_offset++;
                 // Remove post from sticky posts array
                 $offset = array_search($sticky_post->ID, $sticky_posts);
                 unset($sticky_posts[$offset]);
             }
         }
         // If any posts have been excluded specifically, Ignore those that are sticky.
         if (!empty($sticky_posts) && !empty($q['post__not_in'])) {
             $sticky_posts = array_diff($sticky_posts, $q['post__not_in']);
         }
         // Fetch sticky posts that weren't in the query results
         if (!empty($sticky_posts)) {
             $stickies__in = implode(',', array_map('absint', $sticky_posts));
             // honor post type(s) if not set to any
             $stickies_where = '';
             if ('any' != $post_type && '' != $post_type) {
                 if (is_array($post_type)) {
                     $post_types = join("', '", $post_type);
                 } else {
                     $post_types = $post_type;
                 }
                 $stickies_where = "AND {$wpdb->posts}.post_type IN ('" . $post_types . "')";
             }
             $stickies = $wpdb->get_results("SELECT * FROM {$wpdb->posts} WHERE {$wpdb->posts}.ID IN ({$stickies__in}) {$stickies_where}");
             foreach ($stickies as $sticky_post) {
                 // Ignore sticky posts the current user cannot read or are not published.
                 if ('publish' != $sticky_post->post_status) {
                     continue;
                 }
                 array_splice($this->posts, $sticky_offset, 0, array($sticky_post));
                 $sticky_offset++;
             }
         }
     }
     if (!$q['suppress_filters']) {
         $this->posts = apply_filters_ref_array('the_posts', array($this->posts, &$this));
     }
     $this->post_count = count($this->posts);
     // Always sanitize
     foreach ($this->posts as $i => $post) {
         $this->posts[$i] = sanitize_post($post, 'raw');
     }
     if ($q['cache_results']) {
         update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);
     }
     if ($this->post_count > 0) {
         $this->post = $this->posts[0];
     }
     return $this->posts;
 }
Ejemplo n.º 5
0
 /**
  * Turns a first-order date query into SQL for a WHERE clause.
  *
  * @since  4.1.0
  * @access protected
  *
  * @param  array $query        Date query clause.
  * @param  array $parent_query Parent query of the current date query.
  * @return array {
  *     Array containing JOIN and WHERE SQL clauses to append to the main query.
  *
  *     @type string $join  SQL fragment to append to the main JOIN clause.
  *     @type string $where SQL fragment to append to the main WHERE clause.
  * }
  */
 protected function get_sql_for_clause($query, $parent_query)
 {
     global $wpdb;
     // The sub-parts of a $where part.
     $where_parts = array();
     $column = !empty($query['column']) ? esc_sql($query['column']) : $this->column;
     $column = $this->validate_column($column);
     $compare = $this->get_compare($query);
     $inclusive = !empty($query['inclusive']);
     // Assign greater- and less-than values.
     $lt = '<';
     $gt = '>';
     if ($inclusive) {
         $lt .= '=';
         $gt .= '=';
     }
     // Range queries.
     if (!empty($query['after'])) {
         $where_parts[] = $wpdb->prepare("{$column} {$gt} %s", $this->build_mysql_datetime($query['after'], !$inclusive));
     }
     if (!empty($query['before'])) {
         $where_parts[] = $wpdb->prepare("{$column} {$lt} %s", $this->build_mysql_datetime($query['before'], $inclusive));
     }
     // Specific value queries.
     if (isset($query['year']) && ($value = $this->build_value($compare, $query['year']))) {
         $where_parts[] = "YEAR( {$column} ) {$compare} {$value}";
     }
     if (isset($query['month']) && ($value = $this->build_value($compare, $query['month']))) {
         $where_parts[] = "MONTH( {$column} ) {$compare} {$value}";
     } elseif (isset($query['monthnum']) && ($value = $this->build_value($compare, $query['monthnum']))) {
         $where_parts[] = "MONTH( {$column} ) {$compare} {$value}";
     }
     if (isset($query['week']) && false !== ($value = $this->build_value($compare, $query['week']))) {
         $where_parts[] = _wp_mysql_week($column) . " {$compare} {$value}";
     } elseif (isset($query['w']) && false !== ($value = $this->build_value($compare, $query['w']))) {
         $where_parts[] = _wp_mysql_week($column) . " {$compare} {$value}";
     }
     if (isset($query['dayofyear']) && ($value = $this->build_value($compare, $query['dayofyear']))) {
         $where_parts[] = "DAYOFYEAR( {$column} ) {$compare} {$value}";
     }
     if (isset($query['day']) && ($value = $this->build_value($compare, $query['day']))) {
         $where_parts[] = "DAYOFMONTH( {$column} ) {$compare} {$value}";
     }
     if (isset($query['dayofweek']) && ($value = $this->build_value($compare, $query['dayofweek']))) {
         $where_parts[] = "DAYOFWEEK( {$column} ) {$compare} {$value}";
     }
     if (isset($query['dayofweek_iso']) && ($value = $this->build_value($compare, $query['dayofweek_iso']))) {
         $where_parts[] = "WEEKDAY( {$column} ) + 1 {$compare} {$value}";
     }
     if (isset($query['hour']) || isset($query['minute']) || isset($query['second'])) {
         // Avoid notices.
         foreach (array('hour', 'minute', 'second') as $unit) {
             if (!isset($query[$unit])) {
                 $query[$unit] = null;
             }
         }
         if ($time_query = $this->build_time_query($column, $compare, $query['hour'], $query['minute'], $query['second'])) {
             $where_parts[] = $time_query;
         }
     }
     /*
      * Return an array of 'join' and 'where' for compatibility
      * with other query classes.
      */
     return array('where' => $where_parts, 'join' => array());
 }
Ejemplo n.º 6
0
 /**
  * Turns a single date subquery into pieces for a WHERE clause.
  *
  * @since 3.7.0
  * return array
  */
 protected function get_sql_for_subquery($query)
 {
     global $wpdb;
     // The sub-parts of a $where part
     $where_parts = array();
     $column = !empty($query['column']) ? esc_sql($query['column']) : $this->column;
     $column = $this->validate_column($column);
     $compare = $this->get_compare($query);
     $lt = '<';
     $gt = '>';
     if (!empty($query['inclusive'])) {
         $lt .= '=';
         $gt .= '=';
     }
     // Range queries
     if (!empty($query['after'])) {
         $where_parts[] = $wpdb->prepare("{$column} {$gt} %s", $this->build_mysql_datetime($query['after'], true));
     }
     if (!empty($query['before'])) {
         $where_parts[] = $wpdb->prepare("{$column} {$lt} %s", $this->build_mysql_datetime($query['before'], false));
     }
     // Specific value queries
     if (isset($query['year']) && ($value = $this->build_value($compare, $query['year']))) {
         $where_parts[] = "YEAR( {$column} ) {$compare} {$value}";
     }
     if (isset($query['month']) && ($value = $this->build_value($compare, $query['month']))) {
         $where_parts[] = "MONTH( {$column} ) {$compare} {$value}";
     }
     // Legacy
     if (isset($query['monthnum']) && ($value = $this->build_value($compare, $query['monthnum']))) {
         $where_parts[] = "MONTH( {$column} ) {$compare} {$value}";
     }
     if (isset($query['week']) && false !== ($value = $this->build_value($compare, $query['week']))) {
         $where_parts[] = _wp_mysql_week($column) . " {$compare} {$value}";
     }
     // Legacy
     if (isset($query['w']) && false !== ($value = $this->build_value($compare, $query['w']))) {
         $where_parts[] = _wp_mysql_week($column) . " {$compare} {$value}";
     }
     if (isset($query['dayofyear']) && ($value = $this->build_value($compare, $query['dayofyear']))) {
         $where_parts[] = "DAYOFYEAR( {$column} ) {$compare} {$value}";
     }
     if (isset($query['day']) && ($value = $this->build_value($compare, $query['day']))) {
         $where_parts[] = "DAYOFMONTH( {$column} ) {$compare} {$value}";
     }
     if (isset($query['dayofweek']) && ($value = $this->build_value($compare, $query['dayofweek']))) {
         $where_parts[] = "DAYOFWEEK( {$column} ) {$compare} {$value}";
     }
     if (isset($query['hour']) || isset($query['minute']) || isset($query['second'])) {
         // Avoid notices
         foreach (array('hour', 'minute', 'second') as $unit) {
             if (!isset($query[$unit])) {
                 $query[$unit] = null;
             }
         }
         if ($time_query = $this->build_time_query($column, $compare, $query['hour'], $query['minute'], $query['second'])) {
             $where_parts[] = $time_query;
         }
     }
     return $where_parts;
 }
Ejemplo n.º 7
0
 /**
  * Retrieve the posts based on query variables.
  *
  * There are a few filters and actions that can be used to modify the post
  * database query.
  *
  * @since 1.5.0
  * @access public
  * @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;
 }
Ejemplo n.º 8
0
 /**
  * Retrieve the gmedia posts based on query variables.
  *
  * There are a few filters and actions that can be used to modify the gmedia
  * database query.
  *
  * 'status' (string|array) - Gmedia status
  * 'author' (int) - Display or Exclude gmedias from several specific authors
  * 'author_name' (string) - Author name (nice_name)
  * 'cat' (int) - comma separated list of positive or negative category IDs. Display posts that have this category(ies)
  * 'category_name' (string) - Display posts that have this category, using category name
  * 'category__in' (array) - use category id. Same as 'cat', but does not accept negative values
  * 'category__not_in (array) - use category id. Exclude multiple categories
  * 'alb' (int) - comma separated list of positive or negative album IDs. Display posts that have this album(s)
  * 'album_name' (string) - Display posts that have this album, using album name
  * 'album__in' (array) - use album id. Same as 'alb'
  * 'album__not_in (array) - use album id. Exclude multiple albums
  * 'tag' (string) - use tag name. Display posts that have "either" of tags separated by comma.
  *         Display posts that have "all" of tags separated by '+'
  * 'tag_id' (int) - use tag id.
  * 'tag__and' (array) - use tag ids. Display posts that are tagged with all listed tags in array
  * 'tag__in' (array) - use tag ids. To display posts from either tags listed in array. Same as 'tag'
  * 'tag__not_in' (array) - use tag ids. Display posts that do not have any of the listed tag ids
  * 'tag_name__and' (array) - use tag names.
  * 'tag_name__in' (array) - use tag names.
  * 'terms_relation' (string) -  allows you to describe the boolean relationship between the taxonomy queries.
  *         Possible values are 'OR', 'AND'.
  * 'gmedia_id' (int) - use gmedia id.
  * 'name' (string) - use gmedia title.
  * 'gmedia__in' (array) - use gmedia ids. Specify posts to retrieve.
  * 'gmedia__not_in' (array) - use gmedia ids. Specify post NOT to retrieve.
  * 'per_page' (int) - number of post to show per page. Use 'per_page'=>-1 to show all posts.
  * 'nopaging' (bool) - show all posts or use pagination. Default value is 'false', use paging.
  * 'page' (int) - number of page. Show the posts that would normally show up just on page X.
  * 'offset' (int) - number of post to displace or pass over. Note: Setting offset parameter will ignore the 'page' parameter.
  * 'order' (string) - Designates the ascending or descending order of the 'orderby' parameter. Defaults to 'DESC'
  * 'orderby' (string) - Sort retrieved posts by parameter. Defaults to 'ID'
  * - 'none' - No order.
  * - 'ID' - Order by gmedia id. Note the captialization.
  * - 'author' - Order by author.
  * - 'title' - Order by title.
  * - 'date' - Order by date.
  * - 'modified' - Order by last modified date.
  * - 'rand' - Random order.
  * - 'gmedia__in' - Order by 'gmedia__in' parameter. Note: 'gmedia__in' parameter must be specified.
  * - 'meta_value' - Note that a 'meta_key=keyname' must also be present in the query. Note also that the sorting will be
  *         alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers
  *         (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect).
  * - 'meta_value_num' - Order by numeric meta value. Also note that a 'meta_key=keyname' must also be present in the query.
  *         This value allows for numerical sorting as noted above in 'meta_value'.
  * 'm' (int) - Up to 14 numbers. YEAR(4) MONTH(2) DAYOFMONTH(2) HOUR(2) MINUTE(2) SECOND(2).
  *         Also you can query with 'year' (int) - 4 digit year; 'monthnum' (int) - Month number (from 1 to 12);
  *         'w' (int) - Week of the year (from 0 to 53); 'day' (int) - Day of the month (from 1 to 31);
  *         'hour' (int) - Hour (from 0 to 23); 'minute' (int) - Minute (from 0 to 60); 'second' (int) - Second (0 to 60).
  * 'meta_key' (string) - Custom field key.
  * 'meta_value' (string) - Custom field value.
  * 'meta_value_num' (number) - Custom field value.
  * 'meta_compare' (string) - Operator to test the 'meta_value'. Possible values are '!=', '>', '>=', '<', or '<='. Default value is '='.
  * 'meta_query' (array) - Custom field parameters (array of associative arrays):
  * - 'key' (string) The meta key
  * - 'value' (string|array) - The meta value (Note: Array support is limited to a compare value of 'IN', 'NOT IN', 'BETWEEN', or 'NOT BETWEEN')
  * - 'compare' (string) - (optional) How to compare the key to the value.
  *              Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'.
  *              Default: '='
  * - 'type' (string) - (optional) The type of the value.
  *              Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'.
  *              Default: 'CHAR'
  * 's' (string) - search string or terms separated by comma. Search exactly string if 'exact' parameter set to true
  * 'fields' (string) - 'ids': return an array of post IDs.
  * 'robots' - bool Default is empty
  *
  * @see get_posts()
  *
  * @return array List of posts.
  */
 function get_gmedias()
 {
     /** @var $wpdb wpdb */
     global $wpdb, $_wp_using_ext_object_cache;
     // First let's clear some variables
     $whichmimetype = '';
     $whichstatus = '';
     $whichauthor = '';
     $where = '';
     $countwhere = '';
     $limits = '';
     $join = '';
     $search = '';
     $groupby = '';
     $fields = '';
     $page = 1;
     $album = array('order' => false, 'alias' => '');
     $array = array('null_tags' => false);
     $keys = array('error', 'status', 'author', 'author_name', 'cat', 'category_name', 'alb', 'album_name', 'tag', 'tag_id', 'terms_relation', 'gmedia_id', 'name', 'page', 'offset', 'm', 'year', 'monthnum', 'w', 'day', 'hour', 'minute', 'second', 'meta_key', 'meta_value', 's', 'fields', 'robots');
     foreach ($keys as $key) {
         if (!isset($array[$key])) {
             $array[$key] = '';
         }
     }
     $array_keys = array('category__in', 'category__not_in', 'album__in', 'album__not_in', 'gmedia__in', 'gmedia__not_in', 'tag__in', 'tag__not_in', 'tag__and', 'tag_name__in', 'tag_name__and', 'author__in', 'author__not_in', 'meta_query');
     foreach ($array_keys as $key) {
         if (!isset($array[$key])) {
             $array[$key] = array();
         }
     }
     $args = func_get_args();
     if (isset($args[0])) {
         $q = array_merge($array, $args[0]);
     } else {
         $q = $array;
     }
     if (!empty($q['robots'])) {
         $is_robots = true;
     }
     $q['gmedia_id'] = absint($q['gmedia_id']);
     $q['year'] = absint($q['year']);
     $q['monthnum'] = absint($q['monthnum']);
     $q['day'] = absint($q['day']);
     $q['w'] = absint($q['w']);
     $q['m'] = absint($q['m']);
     $q['page'] = absint($q['page']);
     $q['cat'] = preg_replace('|[^0-9,-]|', '', $q['cat']);
     // comma separated list of positive or negative integers
     $q['alb'] = preg_replace('|[^0-9,-]|', '', $q['alb']);
     // comma separated list of positive or negative integers
     $q['name'] = trim($q['name']);
     if ('' !== $q['hour']) {
         $q['hour'] = absint($q['hour']);
     }
     if ('' !== $q['minute']) {
         $q['minute'] = absint($q['minute']);
     }
     if ('' !== $q['second']) {
         $q['second'] = absint($q['second']);
     }
     /*if ( ! isset( $q['per_page'] ) ) {
     			$gmOptions   = get_option( 'gmediaOptions' );
     			$q['per_page'] = $gmOptions['per_page_gmedia'];
     		}*/
     if (!isset($q['per_page']) || $q['per_page'] == 0) {
         $q['per_page'] = -1;
     }
     if (!isset($q['nopaging'])) {
         if ($q['per_page'] == -1) {
             $q['nopaging'] = true;
         } else {
             $q['nopaging'] = false;
         }
     }
     $q['per_page'] = (int) $q['per_page'];
     if ($q['per_page'] < -1) {
         $q['per_page'] = abs($q['per_page']);
     }
     // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present.
     if (isset($q['no_found_rows'])) {
         $q['no_found_rows'] = (bool) $q['no_found_rows'];
     } else {
         $q['no_found_rows'] = false;
     }
     switch ($q['fields']) {
         case 'ids':
             $fields = "{$wpdb->prefix}gmedia.ID";
             break;
         default:
             $fields = "{$wpdb->prefix}gmedia.*";
     }
     // 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->prefix}gmedia.date)=" . substr($q['m'], 0, 4);
         if (strlen($q['m']) > 5) {
             $where .= " AND MONTH({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 4, 2);
         }
         if (strlen($q['m']) > 7) {
             $where .= " AND DAYOFMONTH({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 6, 2);
         }
         if (strlen($q['m']) > 9) {
             $where .= " AND HOUR({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 8, 2);
         }
         if (strlen($q['m']) > 11) {
             $where .= " AND MINUTE({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 10, 2);
         }
         if (strlen($q['m']) > 13) {
             $where .= " AND SECOND({$wpdb->prefix}gmedia.date)=" . substr($q['m'], 12, 2);
         }
     }
     if ('' !== $q['hour']) {
         $where .= " AND HOUR({$wpdb->prefix}gmedia.date)='" . $q['hour'] . "'";
     }
     if ('' !== $q['minute']) {
         $where .= " AND MINUTE({$wpdb->prefix}gmedia.date)='" . $q['minute'] . "'";
     }
     if ('' !== $q['second']) {
         $where .= " AND SECOND({$wpdb->prefix}gmedia.date)='" . $q['second'] . "'";
     }
     if ($q['year']) {
         $where .= " AND YEAR({$wpdb->prefix}gmedia.date)='" . $q['year'] . "'";
     }
     if ($q['monthnum']) {
         $where .= " AND MONTH({$wpdb->prefix}gmedia.date)='" . $q['monthnum'] . "'";
     }
     if ($q['day']) {
         $where .= " AND DAYOFMONTH({$wpdb->prefix}gmedia.date)='" . $q['day'] . "'";
     }
     if ('' != $q['name']) {
         $q['name'] = esc_sql($q['name']);
         $where .= " AND {$wpdb->prefix}gmedia.title = '" . $q['name'] . "'";
     }
     if ($q['w']) {
         $where .= ' AND ' . _wp_mysql_week("`{$wpdb->prefix}gmedia`.`date`") . " = '" . $q['w'] . "'";
     }
     // If a gmedia number is specified, load that gmedia
     if ($q['gmedia_id']) {
         $where .= " AND {$wpdb->prefix}gmedia.ID = " . $q['gmedia_id'];
     } elseif ($q['gmedia__in']) {
         if (!is_array($q['gmedia__in'])) {
             $q['gmedia__in'] = explode(',', $q['gmedia__in']);
         }
         $gmedia__in = implode(',', array_filter(array_map('absint', $q['gmedia__in'])));
         $where .= " AND {$wpdb->prefix}gmedia.ID IN ({$gmedia__in})";
     } elseif ($q['gmedia__not_in']) {
         if (!is_array($q['gmedia__not_in'])) {
             $q['gmedia__not_in'] = explode(',', $q['gmedia__not_in']);
         }
         $gmedia__not_in = implode(',', array_filter(array_map('absint', $q['gmedia__not_in'])));
         $where .= " AND {$wpdb->prefix}gmedia.ID NOT IN ({$gmedia__not_in})";
     }
     // 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['exact'])) {
             $q['search_terms'] = array_filter(array_map('trim', explode(' ', $q['s'])));
         } else {
             $q['search_terms'] = $q['s'];
         }
         $n = '%';
         $searchand = '';
         foreach ((array) $q['search_terms'] as $term) {
             $term = esc_sql(addcslashes($term, '_%\\'));
             $search .= "{$searchand}(({$wpdb->prefix}gmedia.title LIKE '{$n}{$term}{$n}') OR ({$wpdb->prefix}gmedia.description LIKE '{$n}{$term}{$n}') OR ({$wpdb->prefix}gmedia.gmuid LIKE '{$n}{$term}{$n}'))";
             $searchand = ' AND ';
         }
         if (!empty($search)) {
             $search = " AND ({$search}) ";
             /* TODO not display private media when user not logged in
             			if ( !is_user_logged_in() )
             				$search .= " AND ({$wpdb->prefix}gmedia_meta.password = '') ";
             			*/
         }
     }
     // Category stuff
     if (!empty($q['category_name'])) {
         $q['category_name'] = "'" . esc_sql($q['category_name']) . "'";
         $cat = $wpdb->get_var("\n\t\t\t\t\tSELECT term_id\n\t\t\t\t\tFROM {$wpdb->prefix}gmedia_term\n\t\t\t\t\tWHERE taxonomy = 'gmedia_category'\n\t\t\t\t\tAND name = {$q['category_name']}\n\t\t\t\t");
         if ($cat) {
             $q['category__in'][] = $cat;
         }
     }
     if (!empty($q['cat']) && '0' != $q['cat']) {
         $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;
             } else {
                 $q['category__not_in'][] = $cat;
             }
         }
         $q['cat'] = implode(',', $req_cats);
     } elseif ('0' == $q['cat']) {
         $q['category__not_in'] = $this->get_terms('gmedia_category', array('fields' => 'ids'));
     }
     if (!empty($q['category__in']) || '0' == $q['category__in']) {
         $q['category__in'] = wp_parse_id_list($q['category__in']);
         if (in_array(0, $q['category__in'])) {
             $q['category__in'] = array_filter($q['category__in']);
             $q['category__not_in'] = array_diff($this->get_terms('gmedia_category', array('fields' => 'ids')), $q['category__in']);
             $q['category__in'] = array();
         }
     }
     if (!empty($q['category__not_in']) || '0' == $q['category__not_in']) {
         $q['category__not_in'] = wp_parse_id_list($q['category__not_in']);
         if (in_array(0, $q['category__not_in'])) {
             $q['category__not_in'] = array_filter($q['category__not_in']);
             $q['category__in'] = array_diff($this->get_terms('gmedia_category', array('fields' => 'ids')), $q['category__not_in']);
             $q['category__not_in'] = array();
         }
     }
     if (!empty($q['category__in'])) {
         $tax_query[] = array('taxonomy' => 'gmedia_category', 'terms' => $q['category__in'], 'operator' => 'IN');
     }
     if (!empty($q['category__not_in'])) {
         $tax_query[] = array('taxonomy' => 'gmedia_category', 'terms' => $q['category__not_in'], 'operator' => 'NOT IN');
     }
     // Album stuff
     if (!empty($q['album_name'])) {
         $q['album_name'] = "'" . esc_sql($q['album_name']) . "'";
         $alb = $wpdb->get_var("\n\t\t\t\t\tSELECT term_id\n\t\t\t\t\tFROM {$wpdb->prefix}gmedia_term\n\t\t\t\t\tWHERE taxonomy = 'gmedia_album'\n\t\t\t\t\tAND name = {$q['album_name']}\n\t\t\t\t");
         if ($alb) {
             $q['album__in'][] = $alb;
         }
     }
     if (!empty($q['alb']) && '0' != $q['alb']) {
         $q['alb'] = '' . urldecode($q['alb']) . '';
         $q['alb'] = addslashes_gpc($q['alb']);
         $alb_array = preg_split('/[,\\s]+/', $q['alb']);
         $q['alb'] = '';
         $req_albs = array();
         foreach ((array) $alb_array as $alb) {
             if (!($alb = intval($alb))) {
                 continue;
             }
             $in = $alb >= 0;
             $alb = abs($alb);
             if ($in) {
                 /*if(isset($q['album__status'])){
                 			$alb_obj = $this->get_term($alb, 'gmedia_album');
                 			if(empty($alb_obj) || (is_wp_error($alb_obj) || !in_array($alb_obj->status, (array) $q['album__status']))){
                 				continue;
                 			}
                 		}*/
                 $q['album__in'][] = $alb;
                 $req_albs[] = $alb;
             } else {
                 $q['album__not_in'][] = $alb;
                 $req_albs[] = -$alb;
             }
         }
         $q['alb'] = implode(',', $req_albs);
     } elseif ('0' == $q['alb']) {
         $q['album__not_in'] = $this->get_terms('gmedia_album', array('fields' => 'ids'));
     }
     if (!empty($q['album__in']) || '0' == $q['album__in']) {
         $q['album__in'] = wp_parse_id_list($q['album__in']);
         $without_album = in_array(0, $q['album__in']) ? true : false;
         if (isset($q['album__status'])) {
             $q['album__in'] = $this->get_terms('gmedia_album', array('fields' => 'ids', 'orderby' => 'include', 'include' => $q['album__in'], 'status' => $q['album__status']));
         }
         if ($without_album) {
             $q['album__in'] = array_filter($q['album__in']);
             $q['album__not_in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids')), $q['album__in']);
             $q['album__in'] = array();
         }
     }
     if (!empty($q['album__not_in']) || '0' == $q['album__not_in']) {
         $q['album__not_in'] = wp_parse_id_list($q['album__not_in']);
         if (in_array(0, $q['album__not_in'])) {
             $q['album__not_in'] = array_filter($q['album__not_in']);
             if (isset($q['album__status'])) {
                 $q['album__in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids', 'status' => $q['album__status'])), $q['album__not_in']);
             } else {
                 $q['album__in'] = array_diff($this->get_terms('gmedia_album', array('fields' => 'ids')), $q['album__not_in']);
             }
             $q['album__not_in'] = array();
         }
     }
     if (!empty($q['album__in'])) {
         $tax_query[] = array('taxonomy' => 'gmedia_album', 'terms' => $q['album__in'], 'operator' => 'IN');
         if (1 == count($q['album__in'])) {
             $album['order'] = true;
         }
     }
     if (!empty($q['album__not_in'])) {
         $tax_query[] = array('taxonomy' => 'gmedia_album', 'terms' => $q['album__not_in'], 'operator' => 'NOT IN');
     }
     // Tag stuff
     if ('' != $q['tag']) {
         if (strpos($q['tag'], ',') !== false) {
             $tags = preg_split('/[,\\s]+/', $q['tag']);
             foreach ((array) $tags as $tag) {
                 $q['tag_name__in'][] = $tag;
             }
         } else {
             if (preg_match('/[+\\s]+/', $q['tag']) || !empty($q['alb'])) {
                 $tags = preg_split('/[+\\s]+/', $q['tag']);
                 foreach ((array) $tags as $tag) {
                     $q['tag_name__and'][] = $tag;
                 }
             } else {
                 $q['tag_name__in'][] = $q['tag'];
             }
         }
     }
     if (!empty($q['tag_id'])) {
         $q['tag_id'] = array(absint($q['tag_id']));
         $tax_query[] = array('taxonomy' => 'gmedia_tag', 'terms' => $q['tag_id'], 'operator' => 'IN');
     }
     if (!empty($q['tag__in'])) {
         $q['tag__in'] = wp_parse_id_list($q['tag__in']);
         $tax_query[] = array('taxonomy' => 'gmedia_tag', 'terms' => $q['tag__in'], 'operator' => 'IN');
     }
     if (!empty($q['tag__not_in'])) {
         $q['tag__not_in'] = wp_parse_id_list($q['tag__not_in']);
         $tax_query[] = array('taxonomy' => 'gmedia_tag', 'terms' => $q['tag__not_in'], 'operator' => 'NOT IN');
     }
     if (!empty($q['tag__and'])) {
         $q['tag__and'] = wp_parse_id_list($q['tag__and']);
         $tax_query[] = array('taxonomy' => 'gmedia_tag', 'terms' => $q['tag__and'], 'operator' => 'AND');
     }
     if (!empty($q['tag_name__in'])) {
         $q['tag_name__in'] = "'" . implode("','", array_map('esc_sql', array_unique((array) $q['tag_name__in']))) . "'";
         $q['tag_name__in'] = $wpdb->get_col("\n\t\t\t\t\tSELECT term_id\n\t\t\t\t\tFROM {$wpdb->prefix}gmedia_term\n\t\t\t\t\tWHERE taxonomy = 'gmedia_tag'\n\t\t\t\t\tAND name IN ({$q['tag_name__in']})\n\t\t\t\t");
         if (empty($q['tag_name__in']) && $q['null_tags']) {
             return $q['tag_name__in'];
         }
         $tax_query[] = array('taxonomy' => 'gmedia_tag', 'terms' => $q['tag_name__in'], 'operator' => 'IN');
     }
     if (!empty($q['tag_name__and'])) {
         $q['tag_name__and'] = "'" . implode("','", array_map('esc_sql', array_unique((array) $q['tag_name__and']))) . "'";
         $q['tag_name__and'] = $wpdb->get_col("\n\t\t\t\t\tSELECT term_id\n\t\t\t\t\tFROM {$wpdb->prefix}gmedia_term\n\t\t\t\t\tWHERE taxonomy = 'gmedia_tag'\n\t\t\t\t\tAND name IN ({$q['tag_name__and']})\n\t\t\t\t");
         if (empty($q['tag_name__and']) && $q['null_tags']) {
             return $q['tag_name__and'];
         }
         $tax_query[] = array('taxonomy' => 'gmedia_tag', 'terms' => $q['tag_name__and'], 'operator' => 'AND');
     }
     if (!empty($tax_query)) {
         if (isset($q['terms_relation']) && strtoupper($q['terms_relation']) == 'OR') {
             $terms_relation = 'OR';
         } else {
             $terms_relation = 'AND';
         }
         $clauses['join'] = '';
         $clauses['where'] = array();
         $i = 0;
         foreach ($tax_query as $query) {
             /** @var $taxonomy
              * @var  $terms
              * @var  $field
              * @var  $operator
              * @var  $include_children
              */
             extract($query);
             $this->filter_tax[$taxonomy] = true;
             if ('IN' == $operator) {
                 if (empty($terms)) {
                     continue;
                 }
                 $terms = implode(',', $terms);
                 $alias = $i ? 'tr' . $i : 'tr';
                 $clauses['join'] .= " INNER JOIN {$wpdb->prefix}gmedia_term_relationships AS {$alias}";
                 $clauses['join'] .= " ON ({$wpdb->prefix}gmedia.ID = {$alias}.gmedia_id)";
                 $clauses['where'][] = "{$alias}.gmedia_term_id {$operator} ({$terms})";
                 if ($album['order'] && 'gmedia_album' == $taxonomy) {
                     $album['alias'] = $alias;
                     if ('ids' != $q['fields']) {
                         $fields .= ", {$alias}.*";
                     }
                 }
             } elseif ('NOT IN' == $operator) {
                 if (empty($terms)) {
                     continue;
                 }
                 $terms = implode(',', $terms);
                 $clauses['where'][] = "{$wpdb->prefix}gmedia.ID NOT IN (\n\t\t\t\t\t\tSELECT gmedia_id\n\t\t\t\t\t\tFROM {$wpdb->prefix}gmedia_term_relationships\n\t\t\t\t\t\tWHERE gmedia_term_id IN ({$terms})\n\t\t\t\t\t)";
             } elseif ('AND' == $operator) {
                 if (empty($terms)) {
                     continue;
                 }
                 $num_terms = count($terms);
                 $terms = implode(',', $terms);
                 $clauses['where'][] = "(\n\t\t\t\t\t\tSELECT COUNT(1)\n\t\t\t\t\t\tFROM {$wpdb->prefix}gmedia_term_relationships\n\t\t\t\t\t\tWHERE gmedia_term_id IN ({$terms})\n\t\t\t\t\t\tAND gmedia_id = {$wpdb->prefix}gmedia.ID\n\t\t\t\t\t) = {$num_terms}";
             }
             $i++;
         }
         if (!empty($clauses['where'])) {
             $clauses['where'] = ' AND ( ' . implode(" {$terms_relation} ", $clauses['where']) . ' )';
         } else {
             $clauses['where'] = '';
         }
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     // Meta stuff
     $meta_query = array();
     // Simple query needs to be first for orderby=meta_value to work correctly
     foreach (array('key', 'compare', 'type') as $key) {
         if (!empty($q["meta_{$key}"])) {
             $meta_query[0][$key] = $q["meta_{$key}"];
         }
     }
     // Query sets 'meta_value' = '' by default
     if (isset($q['meta_value']) && !empty($q['meta_value'])) {
         $meta_query[0]['value'] = $q['meta_value'];
     }
     if (!empty($q['meta_query']) && is_array($q['meta_query'])) {
         $meta_query = array_merge($meta_query, $q['meta_query']);
     }
     if (!empty($meta_query)) {
         $primary_table = $wpdb->prefix . 'gmedia';
         $primary_id_column = 'ID';
         $meta_table = $wpdb->prefix . 'gmedia_meta';
         $meta_id_column = 'gmedia_id';
         if (isset($meta_query['relation']) && strtoupper($meta_query['relation']) == 'OR') {
             $relation = 'OR';
         } else {
             $relation = 'AND';
         }
         $meta_query = array_filter($meta_query, 'is_array');
         $clauses['join'] = array();
         $clauses['where'] = array();
         foreach ($meta_query as $key => $query) {
             if (!isset($query['key']) || empty($query['key'])) {
                 continue;
             }
             $meta_key = trim($query['key']);
             $meta_type = isset($query['type']) ? strtoupper($query['type']) : 'CHAR';
             if ('NUMERIC' == $meta_type) {
                 $meta_type = 'SIGNED';
             } elseif (!in_array($meta_type, array('BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'))) {
                 $meta_type = 'CHAR';
             }
             $i = count($clauses['join']);
             $alias = $i ? 'mt' . $i : $meta_table;
             // Set JOIN
             $clauses['join'][$i] = "INNER JOIN {$meta_table}";
             $clauses['join'][$i] .= $i ? " AS {$alias}" : '';
             $clauses['join'][$i] .= " ON ({$primary_table}.{$primary_id_column} = {$alias}.{$meta_id_column})";
             $clauses['where'][$key] = '';
             if (!empty($meta_key)) {
                 $clauses['where'][$key] = $wpdb->prepare("{$alias}.meta_key = %s", $meta_key);
             }
             if (!isset($query['value'])) {
                 if (empty($clauses['where'][$key])) {
                     unset($clauses['join'][$i]);
                 }
                 continue;
             }
             $meta_value = $query['value'];
             $meta_compare = is_array($meta_value) ? 'IN' : '=';
             if (isset($query['compare'])) {
                 $meta_compare = strtoupper($query['compare']);
             }
             if (!in_array($meta_compare, array('=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) {
                 $meta_compare = '=';
             }
             if (in_array($meta_compare, array('IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'))) {
                 if (!is_array($meta_value)) {
                     $meta_value = preg_split('/[,\\s]+/', $meta_value);
                 }
                 if (empty($meta_value)) {
                     unset($clauses['join'][$i]);
                     continue;
                 }
             } else {
                 $meta_value = trim($meta_value);
             }
             if ('IN' == substr($meta_compare, -2)) {
                 $meta_compare_string = '(' . substr(str_repeat(',%s', count($meta_value)), 1) . ')';
             } elseif ('BETWEEN' == substr($meta_compare, -7)) {
                 $meta_value = array_slice($meta_value, 0, 2);
                 $meta_compare_string = '%s AND %s';
             } elseif ('LIKE' == substr($meta_compare, -4)) {
                 $meta_value = '%' . addcslashes($meta_value, '_%\\') . '%';
                 $meta_compare_string = '%s';
             } else {
                 $meta_compare_string = '%s';
             }
             if (!empty($clauses['where'][$key])) {
                 $clauses['where'][$key] .= ' AND ';
             }
             $clauses['where'][$key] = ' (' . $clauses['where'][$key] . $wpdb->prepare("CAST({$alias}.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value);
         }
         $clauses['where'] = array_filter($clauses['where']);
         if (empty($clauses['where'])) {
             $clauses['where'] = '';
         } else {
             $clauses['where'] = ' AND (' . implode("\n{$relation} ", $clauses['where']) . ' )';
         }
         $clauses['join'] = implode("\n", $clauses['join']);
         if (!empty($clauses['join'])) {
             $clauses['join'] = ' ' . $clauses['join'];
         }
         $join .= $clauses['join'];
         $where .= $clauses['where'];
     }
     unset($clauses);
     if (!empty($tax_query) || !empty($meta_query)) {
         $groupby = "{$wpdb->prefix}gmedia.ID";
     }
     // Status
     if ($q['status']) {
         $q['status'] = "'" . implode("','", array_map('esc_sql', array_unique((array) $q['status']))) . "'";
         $whichstatus .= " AND {$wpdb->prefix}gmedia.status IN ({$q['status']})";
     }
     // Author/user stuff for ID
     if (!empty($q['author']) && $q['author'] != '0') {
         $q['author'] = addslashes_gpc('' . urldecode($q['author']));
         $authors = array_unique(array_map('intval', preg_split('/[,\\s]+/', $q['author'])));
         foreach ($authors as $author) {
             $key = $author > 0 ? 'author__in' : 'author__not_in';
             $q[$key][] = abs($author);
         }
         $q['author'] = implode(',', $authors);
     }
     if (!empty($q['author__not_in'])) {
         $author__not_in = implode(',', array_map('absint', array_unique((array) $q['author__not_in'])));
         $whichauthor .= " AND {$wpdb->prefix}gmedia.author NOT IN ({$author__not_in}) ";
     } elseif (!empty($q['author__in'])) {
         $author__in = implode(',', array_map('absint', array_unique((array) $q['author__in'])));
         $whichauthor .= " AND {$wpdb->prefix}gmedia.author IN ({$author__in}) ";
     }
     // Author stuff for name
     if ('' != $q['author_name']) {
         $q['author_name'] = esc_sql($q['author_name']);
         $q['author'] = get_user_by('slug', $q['author_name']);
         if ($q['author']) {
             $q['author'] = $q['author']->ID;
         }
         $whichauthor .= " AND ({$wpdb->prefix}gmedia.author = " . absint($q['author']) . ')';
     }
     // MIME-Type stuff
     if (isset($q['mime_type']) && !empty($q['mime_type'])) {
         $whichmimetype = $this->gmedia_mime_type_where($q['mime_type'], $wpdb->prefix . 'gmedia');
     }
     $where .= $whichstatus . $search;
     if (empty($q['order']) || strtoupper($q['order']) != 'ASC' && strtoupper($q['order']) != 'DESC') {
         $q['order'] = 'DESC';
     }
     // Order by
     if (empty($q['orderby']) || 'none' == $q['orderby']) {
         $orderby = "{$wpdb->prefix}gmedia.ID " . $q['order'];
     } else {
         // Used to filter values TODO make orderby comment count
         $allowed_keys = array('ID', 'author', 'date', 'title', 'filename', 'gmuid', 'modified', 'mime_type', 'gmedia__in', 'rand');
         if ($album['order'] && !empty($album['alias'])) {
             $allowed_keys[] = 'custom';
         }
         if (!empty($q['meta_key'])) {
             $allowed_keys[] = $q['meta_key'];
             $allowed_keys[] = 'meta_value';
             $allowed_keys[] = 'meta_value_num';
         }
         $q['orderby'] = urldecode($q['orderby']);
         $q['orderby'] = addslashes_gpc($q['orderby']);
         $orderby_array = array();
         foreach (explode(' ', $q['orderby']) as $orderby) {
             // Only allow certain values for safety
             if (!in_array($orderby, $allowed_keys)) {
                 continue;
             }
             switch ($orderby) {
                 case 'rand':
                     $orderby = 'RAND()';
                     break;
                 case $q['meta_key']:
                 case 'meta_value':
                     $orderby = "{$wpdb->prefix}gmedia_meta.meta_value";
                     break;
                 case 'meta_value_num':
                     $orderby = "{$wpdb->prefix}gmedia_meta.meta_value+0";
                     break;
                 case 'gmedia__in':
                     if (count($q['gmedia__in']) > 1) {
                         $orderby = "FIELD({$wpdb->prefix}gmedia.ID, " . join(', ', $q['gmedia__in']) . ")";
                     } else {
                         $orderby = "{$wpdb->prefix}gmedia.ID";
                     }
                     break;
                 case 'filename':
                     $orderby = "{$wpdb->prefix}gmedia.gmuid";
                     break;
                 case 'custom':
                     $orderby = "{$album['alias']}.gmedia_order {$q['order']}, {$wpdb->prefix}gmedia.ID";
                     break;
                 default:
                     $orderby = "{$wpdb->prefix}gmedia." . $orderby;
             }
             $orderby_array[] = $orderby;
         }
         $orderby = implode(',', $orderby_array);
         if (empty($orderby)) {
             $orderby = "{$wpdb->prefix}gmedia.ID " . $q['order'];
         } else {
             $orderby .= " {$q['order']}";
         }
     }
     // Paging
     if (empty($q['nopaging'])) {
         $page = absint($q['page']);
         if (empty($page)) {
             $page = 1;
         }
         if (empty($q['offset'])) {
             $pgstrt = ($page - 1) * $q['per_page'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['per_page'];
         } else {
             // we're ignoring $page and using 'offset'
             $q['offset'] = absint($q['offset']);
             $pgstrt = $q['offset'] . ', ';
             $limits = 'LIMIT ' . $pgstrt . $q['per_page'];
         }
     }
     // Announce current selection parameters.  For use by caching plugins.
     do_action('gmedia_selection', $where . $whichauthor . $whichmimetype . $groupby . $orderby . $limits . $join);
     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';
     }
     $request = " SELECT {$found_rows} {$fields} FROM {$wpdb->prefix}gmedia {$join} WHERE 1=1 {$where} {$whichauthor} {$whichmimetype} {$groupby} {$orderby} {$limits}";
     $clauses = compact('join', 'where', 'whichauthor', 'whichmimetype', 'groupby', 'orderby', 'limits');
     $this->clauses = $clauses;
     if ('ids' == $q['fields']) {
         $gmedias = $wpdb->get_col($request);
         return $gmedias;
     }
     if (!empty($clauses['where']) || !empty($clauses['whichmimetype'])) {
         $this->filter = true;
     }
     $gmedias = $wpdb->get_results($request);
     if (!$q['no_found_rows'] && !empty($limits)) {
         $this->totalResult = $wpdb->get_var('SELECT FOUND_ROWS()');
         $this->resultPerPage = $q['per_page'];
         $this->pages = ceil($this->totalResult / $q['per_page']);
         $this->openPage = $page;
     }
     $gmedia_count = $this->gmediaCount = count($gmedias);
     if (!isset($q['cache_results'])) {
         if ($_wp_using_ext_object_cache) {
             $q['cache_results'] = false;
         } else {
             $q['cache_results'] = true;
         }
     }
     if (!isset($q['update_gmedia_term_cache'])) {
         $q['update_gmedia_term_cache'] = true;
     }
     if (!isset($q['update_gmedia_meta_cache'])) {
         $q['update_gmedia_meta_cache'] = true;
     }
     if ($q['cache_results']) {
         $this->update_gmedia_caches($gmedias, $q['update_gmedia_term_cache'], $q['update_gmedia_meta_cache']);
     }
     if ($gmedia_count > 0) {
         $this->gmedia = $gmedias[0];
     }
     $this->query = $gmedias;
     return $gmedias;
 }