Skip to content

Instantly share code, notes, and snippets.

@bitardev
Created July 26, 2024 07:14
Show Gist options
  • Select an option

  • Save bitardev/487fa5aee2a6e2c2c13bbce4780f1fa2 to your computer and use it in GitHub Desktop.

Select an option

Save bitardev/487fa5aee2a6e2c2c13bbce4780f1fa2 to your computer and use it in GitHub Desktop.
A challenging problem encountered on the BusinessLeague Project

Script Documentation: JSON Data Generation and Caching

Overview

This script fetches data from an external API, processes it, and writes it to .json files. The purpose of this script is to reduce API loading times on a website by pre-fetching data and storing it locally. This script is intended to be scheduled as a daily cron job.

  1. AJAX Handler (getMatchlistBySeason) : This function handles AJAX requests to fetch match data for a specific season. It retrieves match data in a loop until it gets the desired number of matches ($limit). It then processes and formats the data, including match results, team names, logos, and league names. The processed data is returned as a JSON response.
  2. getJSONByLink Function : This helper function makes HTTP GET requests to a given URL, retrieves the response body, and decodes it from JSON to an associative array. It’s used extensively throughout your other functions to fetch data from the API.
  3. insert_acf_data_from_sportpress Function : This function hooks into wp_insert_post_data to perform various data operations depending on the page template and ACF (Advanced Custom Fields) options:
  • For template-parts/ligue-division-tpl.php: Generates and saves JSON files containing league standings, goal counts, upcoming matches, and team logos.
  • For template-parts/home-tpl.php: Similar to the above, but specifically for the home page template. It fetches match results and goal counts and saves them as JSON files.
  • For template-parts/ligue-tpl.php: Generates and saves a JSON file with details of different leagues, including team logos.

Key Points:

  • Pagination Handling: The while loops used for fetching data from the API handle pagination to retrieve more data if needed.
  • File Operations: The code writes JSON data to files in the cron directory for further processing or caching.
  • Date Formatting: Dates are formatted to a specific format (d/m/Y G\hi) for display.

Suggestions:

  • Error Handling: Consider adding error handling for API requests and file operations to improve robustness. For example, check if wp_remote_get returns errors or if file operations succeed.
  • Code Refactoring: To make the code more manageable, consider breaking it into smaller functions or using classes. This can help with readability and maintainability.
  • Security: Ensure proper validation and sanitization of any user inputs or outputs, especially in contexts where data is returned via AJAX or manipulated.
<?php
/**
* Custom template scripts for this theme
*
* Eventually, some of the functionality here could be replaced by core features.
*
* @package BusinessLeague
*/
add_action( 'wp_ajax_getMatchlistBySeason', 'getMatchlistBySeason' );
add_action( 'wp_ajax_nopriv_getMatchlistBySeason', 'getMatchlistBySeason' );
function getMatchlistBySeason() {
$match_list = array();
$limit = 6;
$count_i = 1;
while(count($match_list) < $limit):
$link = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/events?seasons=326&per_page=100&page='.$count_i;
$datas = getJSONByLink($link);
foreach($datas as $match):
if($match["status"] == "publish" && count($match_list) < $limit):
$match_list[] = $match;
else:
break;
endif;
endforeach;
$count_i++;
endwhile;
$count_j = 0;
$match_list_array = array();
foreach($match_list as $match):
$match_data = array();
$leagues = $match["leagues"];
$match_date1 = $match["date"];
$match_date = date('d/m/Y G\hi', strtotime($match_date1));
$match_id = $match["id"];
$team_1 = $match["teams"][0];
$team_2 = $match["teams"][1];
$team_1_result = $match["main_results"][0];
$team_2_result = $match["main_results"][1];
$match_data["team_1_result"] = $team_1_result;
$match_data["team_2_result"] = $team_2_result;
$link_league = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues/'.$league;
$datas_league = getJSONByLink($link_league);
$league_name = $datas_league[0]["name"];
$link_team1 = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_1;
$datas_team1 = getJSONByLink($link_team1);
$team_1_name = $datas_team1["title"]["rendered"];
$team_1_featured_media_id = $datas_team1["featured_media"];
$link_media_team1 = 'https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_1_featured_media_id;
$data_media_team1 = getJSONByLink($link_media_team1);
$team_1_logo = $data_media_team1["guid"]["rendered"];
$match_data["team_1_name"] = $team_1_name;
$match_data["team_1_logo"] = $team_1_logo;
$link_team2 = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_2;
$datas_team2 = getJSONByLink($link_team2);
$team_2_name = $datas_team2["title"]["rendered"];
$team_2_featured_media_id = $datas_team2["featured_media"];
$link_media_team2 = 'https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_2_featured_media_id;
$data_media_team2 = getJSONByLink($link_media_team2);
$team_2_logo = $data_media_team2["guid"]["rendered"];
$match_data["team_2_name"] = $team_2_name;
$match_data["team_2_logo"] = $team_2_logo;
$match_data["league_name"] = $league_name;
$match_data["match_id"] = $match_id;
$match_data["match_date"] = $match_date;
$match_list_array[] = $match_data;
$count_j++;
endforeach;
$response = json_encode($match_list_array, true);
echo $response;
die();
}
function getJSONByLink($link) {
$request = wp_remote_get($link);
$json = wp_remote_retrieve_body( $request );
$response = json_decode($json, true);
return $response;
}
function insert_acf_data_from_sportpress( $data , $postarr ) {
$page_id = $postarr["post_ID"];
$page_template = $postarr["page_template"];
//generate league teams logo/name list
if($page_template == "template-parts/ligue-division-tpl.php"):
// field_5dcc62c94ab42
// field_5dcb28ee4e8ed => local
$options_api = $postarr["acf"]["field_5dcc62c94ab42"];
if(is_array($options_api)):
$saison_data = get_field("saison", $page_id);
$ligue_data = get_field("ligue", $page_id);
$saison_id = $saison_data["value"];
$ligue_id = $ligue_data["value"];
$list_childs_ligue = array(intval($ligue_id));
$leagues = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues?per_page=100');
foreach($leagues as $league): if($league["parent"] == $ligue_id): $list_childs_ligue[] = $league["id"] ;endif; endforeach;
if(in_array("api_1",$options_api)):
// generate classement
$leagues_childs = array();
foreach($list_childs_ligue as $child):
$league_child = getJSONByLink("https://www.businessleague.fr/app/wp-json/sportspress/v2/tables?leagues=".$child."&seasons=".$saison_id);
if( is_array($league_child) && count($league_child) > 0 && count($league_child[0]) > 0 ){
foreach($league_child as $ligue):
$league_childs_array = array();
foreach($ligue["data"] as $key => $division_item):
if($division_item["name"] != "Club"):
$league_child_array = array();
$league_child_array["name"] = $division_item["name"];
$league_child_array["pts"] = $division_item["pts"];
$league_child_array["pos"] = $division_item["pos"];
$league_child_array["p"] = $division_item["p"];
$league_child_array["gd"] = $division_item["gd"];
$league_childs_array[] = $league_child_array;
endif;
endforeach;
$leagues_childs[] = $league_childs_array;
endforeach;
}
endforeach;
$leagues_childs = array("classement" => $leagues_childs);
$leagues_childs_json_file = json_encode($leagues_childs);
$file_full_name = 'league'.$ligue_id.'.json';
$jsonf = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name", "w");
$json_file = dirname( __FILE__ ) . '/../cron/'.$file_full_name;
file_put_contents($json_file, $leagues_childs_json_file);
endif;
if(in_array("api_2",$options_api)):
$goal_counter = 0;
$count_i = 1;
$end = false;
foreach($list_childs_ligue as $child):
$datas = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/events?seasons='.$saison_id.'&leagues='.$child.'&per_page=100');
if(is_array($datas)):
foreach($datas as $match):
if($match["status"] == "publish"):
$main_results = $match["main_results"][0] + $match["main_results"][1];
$goal_counter += $main_results;
endif;
endforeach;
endif;
endforeach;
$datas_total_buts_json_file = json_encode($goal_counter);
$file_full_name8 = 'league'.$ligue_id.'_total_buts.json';
$jsonf8 = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name8", "w");
$json_file8 = dirname( __FILE__ ) . '/../cron/'.$file_full_name8;
file_put_contents($json_file8, $datas_total_buts_json_file);
endif;
if(in_array("api_3",$options_api)):
$limit = 10;
$datas_events = array();
$last_match_list[] = array();
$future_match_list[] = array();
$counter_var = 0;
$datas_event_childs_array = array();
foreach($list_childs_ligue as $child):
$datas_event_child = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/events?seasons='.$saison_id.'&leagues='.$child.'&per_page=100&page=1');
if( is_array($datas_event_child) && count($datas_event_child) > 0 ){
foreach($datas_event_child as $item):
$datas_event_childs_array[] = $item;
endforeach;
}
$counter_var++;
endforeach;
foreach($datas_event_childs_array as $matche):
if($matche["status"] == "publish" && !empty($matche) && count($last_match_list) < $limit):
$count_j = 0;
$match_list_array = array();
$leagues = $matche["leagues"];
$match_date1 = $matche["date"];
$match_date = date('d/m/Y G\hi', strtotime($match_date1));
$match_id = $matche["id"];
$team_1 = $matche["teams"][0];
$team_2 = $matche["teams"][1];
$team_1_result = $matche["main_results"][0];
$team_2_result = $matche["main_results"][1];
$datas_league = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues/'.$league);
$league_name = $datas_league[0]["name"];
$datas_team1 = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_1);
$team_1_name = $datas_team1["title"]["rendered"];
$team_1_featured_media_id = $datas_team1["featured_media"];
$data_media_team1 = getJSONByLink('https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_1_featured_media_id);
$team_1_logo = $data_media_team1["guid"]["rendered"];
$datas_team2 = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_2);
$team_2_name = $datas_team2["title"]["rendered"];
$team_2_featured_media_id = $datas_team2["featured_media"];
$data_media_team2 = getJSONByLink('https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_2_featured_media_id);
$team_2_logo = $data_media_team2["guid"]["rendered"];
$last_match_list[] = array(
"id" => $matche["id"],
"status" => $matche["status"],
"date" => $matche["date"],
"title" => $matche["title"],
"leagues" => $matche["leagues"],
"seasons" => $matche["seasons"],
"venues" => $matche["venues"],
"teams" => $matche["teams"],
"main_results" => $matche["main_results"],
"team_1_result" => $team_1_result,
"team_2_result" => $team_2_result,
"team_1_name" => $team_1_name,
"team_1_logo" => $team_1_logo,
"team_2_name" => $team_2_name,
"team_2_logo" => $team_2_logo,
"league_name" => $league_name,
"match_id" => $match_id,
"match_date" => $match_date
);
endif;
if($matche["status"] == "future" && count($future_match_list) < $limit):
$count_j = 0;
$future_match_list_array = array();
$match_data = array();
$leagues = $matche["leagues"];
$match_date1 = $matche["date"];
$match_date = date('d/m/Y G\hi', strtotime($match_date1));
$match_id = $matche["id"];
$team_1 = $matche["teams"][0];
$team_2 = $matche["teams"][1];
$datas_league = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues/'.$league);
$league_name = $datas_league[0]["name"];
$datas_team1 = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_1);
$team_1_name = $datas_team1["title"]["rendered"];
$team_1_featured_media_id = $datas_team1["featured_media"];
$data_media_team1 = getJSONByLink('https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_1_featured_media_id);
$team_1_logo = $data_media_team1["guid"]["rendered"];
$datas_team2 = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_2);
$team_2_name = $datas_team2["title"]["rendered"];
$team_2_featured_media_id = $datas_team2["featured_media"];
$data_media_team2 = getJSONByLink('https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_2_featured_media_id);
$team_2_logo = $data_media_team2["guid"]["rendered"];
$future_match_list[] = array(
"id" => $matche["id"],
"status" => $matche["status"],
"date" => $matche["date"],
"title" => $matche["title"],
"leagues" => $matche["leagues"],
"seasons" => $matche["seasons"],
"venues" => $matche["venues"],
"teams" => $matche["teams"],
"main_results" => $matche["main_results"],
"team_1_name" => $team_1_name,
"team_1_logo" => $team_1_logo,
"team_2_name" => $team_2_name,
"team_2_logo" => $team_2_logo,
"league_name" => $league_name,
"match_id" => $match_id,
"match_date" => $match_date
);
endif;
endforeach;
$datas_events_array = array(
"published_matchs" => $last_match_list,
"future_matchs" => $future_match_list
);
$datas_events_array_json_file = json_encode($datas_events_array);
$file_full_name2 = 'league'.$ligue_id.'_matchs.json';
$jsonf2 = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name2", "w");
$json_file2 = dirname( __FILE__ ) . '/../cron/'.$file_full_name2;
file_put_contents($json_file2, $datas_events_array_json_file);
endif;
if(in_array("api_4",$options_api)):
$teams_datas_child = array();
foreach($list_childs_ligue as $child):
$teams_data_child = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/teams?seasons='.$saison_id.'&leagues='.$child.'&per_page=100&page=1');
foreach($teams_data_child as $team_data):
if(count($team_data)>0):
$teams_datas_child[] = $team_data;
endif;
endforeach;
endforeach;
$total_teams = count($teams_datas_child);
$team_list_logos = array();
foreach($teams_datas_child as $team):
$team_name = $team["title"]["rendered"];
$media_team = getJSONByLink('https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team["featured_media"]);
$team_logo = $media_team["guid"]["rendered"];
$team_list_logos[] = array(
"logo" => $team_logo,
"name" => $team_name
);
endforeach;
$datas_logos_array_json_file = json_encode($team_list_logos);
$file_full_name3 = 'league'.$ligue_id.'_teams_logo.json';
$jsonf3 = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name3", "w");
$json_file3 = dirname( __FILE__ ) . '/../cron/'.$file_full_name3;
file_put_contents($json_file3, $datas_logos_array_json_file);
endif;
endif;
endif;
if($page_template == "template-parts/home-tpl.php"):
$options_api = $postarr["acf"]["field_5dcc62fdc48d0"];
if(is_array($options_api)):
if(in_array("api_1",$options_api)):
$match_list = array();
$limit = 10;
$count_i = 1;
while(count($match_list) < $limit):
$link = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/events?seasons=326&per_page=100&page='.$count_i;
$datas = getJSONByLink($link);
foreach($datas as $match):
if($match["status"] == "publish" && count($match_list) < $limit):
$match_list[] = $match;
else:
break;
endif;
endforeach;
$count_i++;
endwhile;
$count_j = 0;
$match_list_array = array();
foreach($match_list as $match):
$match_data = array();
// if($count_j == 0):
$leagues = $match["leagues"];
$match_date1 = $match["date"];
$match_date = date('d/m/Y G\hi', strtotime($match_date1));
$match_id = $match["id"];
// $seasons = $match["seasons"];
$team_1 = $match["teams"][0];
$team_2 = $match["teams"][1];
$team_1_result = $match["main_results"][0];
$team_2_result = $match["main_results"][1];
$match_data["team_1_result"] = $team_1_result;
$match_data["team_2_result"] = $team_2_result;
$link_league = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues/'.$league;
$datas_league = getJSONByLink($link_league);
$league_name = $datas_league[0]["name"];
$link_team1 = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_1;
$datas_team1 = getJSONByLink($link_team1);
$team_1_name = $datas_team1["title"]["rendered"];
$team_1_featured_media_id = $datas_team1["featured_media"];
$link_media_team1 = 'https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_1_featured_media_id;
$data_media_team1 = getJSONByLink($link_media_team1);
$team_1_logo = $data_media_team1["guid"]["rendered"];
$match_data["team_1_name"] = $team_1_name;
$match_data["team_1_logo"] = $team_1_logo;
$link_team2 = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/teams/'.$team_2;
$datas_team2 = getJSONByLink($link_team2);
$team_2_name = $datas_team2["title"]["rendered"];
$team_2_featured_media_id = $datas_team2["featured_media"];
$link_media_team2 = 'https://www.businessleague.fr/app/wp-json/wp/v2/media/'.$team_2_featured_media_id;
$data_media_team2 = getJSONByLink($link_media_team2);
$team_2_logo = $data_media_team2["guid"]["rendered"];
$match_data["team_2_name"] = $team_2_name;
$match_data["team_2_logo"] = $team_2_logo;
$match_data["league_name"] = $league_name;
$match_data["match_id"] = $match_id;
$match_data["match_date"] = $match_date;
$match_list_array[] = $match_data;
// endif;
$count_j++;
endforeach;
$match_list_array_json_file = json_encode($match_list_array);
$file_full_name9 = 'result_home.json';
$jsonf9 = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name9", "w");
$json_file9 = dirname( __FILE__ ) . '/../cron/'.$file_full_name9;
file_put_contents($json_file9, $match_list_array_json_file);
endif;
if(in_array("api_2",$options_api)):
$goal_counter = 0;
$count_i = 1;
$end = false;
while($end === false):
$link = 'https://www.businessleague.fr/app/wp-json/sportspress/v2/events?seasons=326&per_page=100&page='.$count_i;
$datas = getJSONByLink($link);
if (array_key_exists('code', $datas)) {
$end = true;
}else{
foreach($datas as $match):
if($match["status"] == "publish"):
$main_results = $match["main_results"][0] + $match["main_results"][1];
$goal_counter += $main_results;
else:
break;
endif;
endforeach;
}
$count_i++;
endwhile;
$goal_counter_json_file = json_encode($goal_counter);
$file_full_name10 = 'total_goals.json';
$jsonf10 = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name10", "w");
$json_file10 = dirname( __FILE__ ) . '/../cron/'.$file_full_name10;
file_put_contents($json_file10, $goal_counter_json_file);
endif;
endif;
endif;
if($page_template == "template-parts/ligue-tpl.php"):
$options_api = $postarr["acf"]["field_5dd06b09ac206"];
if(in_array("api_1",$options_api)):
$liste_ligues_acf = $postarr["acf"]["field_5dbffc554c722"];
$league_list2 = array();
if(is_array($liste_ligues_acf)):
foreach($liste_ligues_acf as $ligue_page_id):
$ligue_data = get_field("ligue", $ligue_page_id);
$ligue_ligue_id = $ligue_data["value"];
// -----------------
$spec_league = getJSONByLink("https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues/".$ligue_ligue_id);
$base_url_tpl = get_template_directory_uri();
$all_teams_logo_per_ligue = getJSONByLink($base_url_tpl.'/cron/league'.$ligue_ligue_id.'_teams_logo.json');
$_name = $spec_league["name"];
$_slug = $spec_league["slug"];
$_teams_logo = array();
$_count = count($all_teams_logo_per_ligue);
foreach($all_teams_logo_per_ligue as $team):
$_teams_logo[] = $team["logo"];
endforeach;
$league_list2[] = array(
"_id" => $ligue_ligue_id,
"_count" => $_count,
"_name" => $_name,
"_slug" => $_slug,
"_logos" => $_teams_logo
);
endforeach;
$datas_logos_json_file = json_encode($league_list2);
$file_full_name4 = 'differentes_ligues.json';
$jsonf4 = fopen(dirname( __FILE__ ) . "/../cron/$file_full_name4", "w");
$json_file4 = dirname( __FILE__ ) . '/../cron/'.$file_full_name4;
file_put_contents($json_file4, $datas_logos_json_file);
endif;
endif;
endif;
return $data;
}
add_filter('wp_insert_post_data','insert_acf_data_from_sportpress', '99', 2 );
function acf_load_ligue_field_choices( $field ) {
$field['choices'] = array();
$leagues = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/leagues?per_page=100');
$leagues_array = array();
foreach($leagues as $league):
if($league["parent"] == 0):
$leagues_array[] = array(
"name" => $league["name"],
"id" => $league["id"]
);
$field['choices'][ $league["id"] ] = $league["name"];
endif;
endforeach;
return $field;
}
add_filter('acf/load_field/name=ligue', 'acf_load_ligue_field_choices');
function acf_load_saison_field_choices( $field ) {
$field['choices'] = array();
$leagues = getJSONByLink('https://www.businessleague.fr/app/wp-json/sportspress/v2/seasons');
foreach($leagues as $league):
if($league["parent"] == 0):
$field['choices'][ $league["id"] ] = "Saison ".$league["name"];
endif;
endforeach;
return $field;
}
add_filter('acf/load_field/name=saison', 'acf_load_saison_field_choices');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment