Last active
February 9, 2023 10:44
-
-
Save temsool/d6407fbc3b6ce22e0a83ef5b53af91f9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
require_once($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php'); | |
$args = array( | |
'numberposts' => 10, | |
'post_type' => 'ag_location', | |
'post_status' => 'publish', | |
'suppress_filters' => true | |
); | |
$posts = get_posts( $args ); | |
$log_file = fopen("log.txt", "a") or die("Unable to open file!"); | |
foreach ($posts as $post) { | |
$location_id = get_field("locationId", $post->ID); | |
$api_url = "https://api.cqc.org.uk/public/v1/locations/".$location_id; | |
$response = wp_remote_get( $api_url ); | |
$data = json_decode( wp_remote_retrieve_body( $response ), true ); | |
if(isset($data["currentRatings"]) && isset($data["currentRatings"]["overall"]) && isset($data["currentRatings"]["overall"]["rating"])) { | |
$api_rating = $data["currentRatings"]["overall"]["rating"]; | |
$existing_rating = get_field("location_latest_overall_rating", $post->ID); | |
if($existing_rating != $api_rating) { | |
$taxonomy = "ag_rating"; | |
$term = get_term_by("slug", $api_rating, $taxonomy); | |
if(!$term) { | |
wp_insert_term($api_rating, $taxonomy, array("slug" => $api_rating)); | |
$term = get_term_by("slug", $api_rating, $taxonomy); | |
} | |
wp_set_post_terms($post->ID, $term->term_id, $taxonomy, false); | |
update_field("location_latest_overall_rating", $api_rating, $post->ID); | |
fwrite($log_file, "Post with ID ".$post->ID." updated.\n"); | |
echo "<br>Post with ID ".$post->ID." updated.<br>"; | |
echo "Old rating: ".$existing_rating."<br>"; | |
echo "New rating: ".$api_rating."<br>"; | |
} else { | |
echo "<br>Post with ID ".$post->ID." was not updated because rating is same as API.<br>"; | |
} | |
} else { | |
echo "<br>Post with ID ".$post->ID." was not updated because API returned unexpected data.<br>"; | |
} | |
sleep(1); | |
} | |
fclose($log_file); | |
?> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment