Auto-fetch next NHL game and update a post
function fetch_nhl_next_game() {
$api_url = ‘https://statsapi.web.nhl.com/api/v1/schedule?expand=schedule.broadcasts&date=’ . date(‘Y-m-d’);

$response = wp_remote_get($api_url);
if (is_wp_error($response)) return;

$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);

if (empty($data[‘dates’][0][‘games’])) return;

$game = $data[‘dates’][0][‘games’][0]; // First upcoming game

$home_team = $game[‘teams’][‘home’][‘team’][‘name’];
$away_team = $game[‘teams’][‘away’][‘team’][‘name’];
$game_date = new DateTime($game[‘gameDate’]);
$broadcasts = $game[‘broadcasts’] ?? [];

$title = “$away_team vs $home_team”;
$content = “

Date: ” . $game_date->format(‘M j, Y \a\t g:i A T’) . “

“;
$content .= “

Watch on: “;

foreach ($broadcasts as $b) {
$content .= $b[‘market’] . “: ” . $b[‘name’] . ” “;
if ($b[‘type’] == ‘national’) $content .= “(National) “;
}

$content .= “
📺 Official Stream (NHL.TV) | ESPN+

“;

// Check if we already have a “Next Game” post
$existing = get_page_by_title(‘Next NHL Game’, OBJECT, ‘nhl_game’);
if ($existing) {
wp_update_post([
‘ID’ => $existing->ID,
‘post_title’ => $title,
‘post_content’ => $content,
‘post_status’ => ‘publish’,
]);
} else {
wp_insert_post([
‘post_title’ => $title,
‘post_content’ => $content,
‘post_type’ => ‘nhl_game’,
‘post_status’ => ‘publish’,
]);
}
}

// Hook into WordPress cron
if (!wp_next_scheduled(‘fetch_nhl_next_game_cron’)) {
wp_schedule_event(time(), ‘twicedaily’, ‘fetch_nhl_next_game_cron’);
}
add_action(‘fetch_nhl_next_game_cron’, ‘fetch_nhl_next_game’);

Back To Top