This function performs a complex SQL query with multiple JOINs to aggregate session statistics. It groups results by game ID to provide summary metrics.
The function uses a LEFT JOIN with de_app_sessions to include games even if they have no sessions. Games without sessions will have sessions_count, total_score, total_duration, and users_count set to 0.
$sql = "SELECT p.ID as id, p.post_title as name, p.post_name as slug, p.post_date as created_at, (SELECT meta_value FROM de_postmeta WHERE post_id = p.ID AND meta_key = '_dilema_fecha_activacion' LIMIT 1) as activation_date, p.post_status as status, p.guid as guid, MAX(c.post_title) as client, (SELECT gp.guid FROM de_posts gp WHERE gp.ID = (SELECT CAST(gpm.meta_value AS UNSIGNED) FROM de_postmeta gpm WHERE gpm.post_id = MAX(c.ID) AND gpm.meta_key = '_thumbnail_id' LIMIT 1)) as client_logo, (SELECT meta_value FROM de_postmeta WHERE post_id = p.ID AND (meta_key = 'dilemma_type' OR meta_key = '_tipo_dilema' OR meta_key = 'tipo') LIMIT 1) as type, COUNT(s.id) as sessions_count, SUM(s.score) as total_score, SUM(s.duration) as total_duration, COUNT(DISTINCT s.userId) as users_countFROM de_posts pLEFT JOIN de_postmeta pm ON p.ID = pm.post_id AND pm.meta_key = '_cliente_asociado'LEFT JOIN de_posts c ON pm.meta_value = c.IDLEFT JOIN de_app_sessions s ON p.ID = s.gameIdWHERE p.post_type = 'dilemas' AND p.post_status = 'publish'GROUP BY p.IDORDER BY p.post_date DESC";
When date filters (start_date or end_date) are provided, the function counts games that have sessions within that date range, not games created in that range.
// Get finished sessions for a game$users = get_game_users(42, 20, 0, '', 'Finished');// Search for specific user$users = get_game_users(42, 10, 0, '[email protected]', '');