Written by Anonymous
//アクセスランキングを取得
if ( !function_exists( 'get_access_ranking_records' ) ):
function get_access_ranking_records($days = 'all', $limit = 5, $type = ET_DEFAULT, $cat_ids = array(), $exclude_post_ids = array(), $exclude_cat_ids = array(), $children = 0, $author = null, $post_type = 'post', $snippet = 0){
global $wpdb;
$access_table = ACCESSES_TABLE_NAME;
//カテゴリー処理
$cat_ids = is_array($cat_ids) ? $cat_ids : array();
if ($children && $cat_ids) {
$res = $cat_ids;
foreach ($cat_ids as $category) {
$res = array_merge($res, get_term_children($category, 'category'));
}
$cat_ids = $res;
}
//除外投稿
$exclude_post_ids = is_array($exclude_post_ids) ? $exclude_post_ids : array();
$archive_exclude_post_ids = get_archive_exclude_post_ids();
if ($archive_exclude_post_ids) {
$exclude_post_ids = array_unique(array_merge($exclude_post_ids, $archive_exclude_post_ids));
}
$where = "WHERE {$access_table}.post_type = '$post_type' ";
if ($days != 'all') {
$date_before = get_current_db_date_before($days);
$date = get_current_db_date();
$where .= " AND {$access_table}.date BETWEEN '$date_before' AND '$date' ";
}
if (!empty($exclude_post_ids)) {
$where .= " AND {$access_table}.post_id NOT IN(".implode(',', $exclude_post_ids).") ";
}
//カテゴリー指定
$join_cat = '';
if (!empty($cat_ids) || !empty($exclude_cat_ids)) {
$term_relationships = $wpdb->term_relationships;
$term_taxonomy = $wpdb->term_taxonomy;
$join_cat = " INNER JOIN $term_relationships ON $term_relationships.object_id = {$access_table}.post_id
INNER JOIN $term_taxonomy ON $term_taxonomy.term_taxonomy_id = $term_relationships.term_taxonomy_id
";
$where .= " AND $term_taxonomy.taxonomy = 'category' ";
if (!empty($cat_ids)) {
$where .= " AND $term_taxonomy.term_id IN (".implode(',', $cat_ids).") ";
}
if (!empty($exclude_cat_ids)) {
$where .= " AND $term_relationships.term_taxonomy_id NOT IN (".implode(',', $exclude_cat_ids).") ";
}
}
if (!is_numeric($limit)) $limit = 5;
// サブクエリでアクセス集計、メインクエリで投稿データ結合
$query = "
SELECT wp_posts.ID, wp_posts.post_title, wp_posts.post_date, wp_posts.post_author, wp_posts.post_status, wp_posts.post_type, wp_posts.comment_count, ranks.sum_count
FROM (
SELECT {$access_table}.post_id, SUM({$access_table}.count) AS sum_count
FROM {$access_table}
$join_cat
$where
GROUP BY {$access_table}.post_id
) AS ranks
INNER JOIN {$wpdb->posts} AS wp_posts ON wp_posts.ID = ranks.post_id
WHERE wp_posts.post_status = 'publish'
ORDER BY ranks.sum_count DESC, wp_posts.post_date DESC
LIMIT %d
";
$records = $wpdb->get_results($wpdb->prepare($query, intval($limit)));
return $records;
}
endif;