public static function get_by_frequency($limit = null, $post_type = null, $min = 1, $max = null, $search = null, $orderby = 'count', $inverse = false)
{
$query = '
SELECT t.*, tp.object_id, count(tp.object_id) as `count`
FROM {terms} t
LEFT JOIN {object_terms} tp ON t.id=tp.term_id
LEFT JOIN {posts} p ON tp.object_id=p.id
LEFT JOIN {object_types} ot ON tp.object_type_id=ot.id and ot.name="post"
WHERE t.vocabulary_id = ?';
$params = array(Tags::vocabulary()->id);
if (isset($post_type)) {
$query .= ' AND p.content_type = ?';
$params[] = Post::type($post_type);
}
if (isset($search)) {
$query .= " AND term_display LIKE ?";
$params[] = '%' . $search . '%';
}
$query .= ' GROUP BY t.id';
if (is_int($min) || is_int($max)) {
$query .= ' HAVING';
}
if (is_int($min)) {
$query .= " count >= {$min}";
}
if (is_int($min) && is_int($max)) {
$query .= ' AND';
}
if (is_int($max)) {
$query .= " count <= {$max}";
}
$valid_orderbys = array('pubdate', 'count', 'term_display');
if (!in_array($orderby, $valid_orderbys)) {
$orderby = 'count';
}
$query .= " ORDER BY `{$orderby}`";
// Inverse both directions so the result is actually reversed tag by tag and not in blocks
if ($inverse) {
$query .= ' ASC, term_display DESC';
} else {
$query .= ' DESC, term_display ASC';
}
if (is_int($limit)) {
$query .= ' LIMIT ' . $limit;
}
$tags = DB::get_results($query, $params, 'Term');
return $tags ? new Terms($tags) : false;
}