Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Class IMDb_Movies
- */
- class IMDb_Movies {
- public $last_update_option_name = "imdb_movies_update_interval_value";
- public $last_update_timestamp;
- /**
- * IMDb_Movies constructor.
- */
- public function __construct() {
- $this->last_update_timestamp = get_option($this->last_update_option_name);
- }
- /**
- * @param $value
- * @param string $unit
- *
- * @return bool
- */
- public function set_update_interval($value, $unit = "seconds") {
- $timestamp_now = time();
- $timestamp_last_update = $this->last_update_timestamp;
- if($unit === "seconds") {
- $seconds = $value;
- }
- elseif($unit === "minutes") {
- $seconds = $value * 60;
- }
- elseif($unit === "hours") {
- $seconds = ($value * 60) * 60;
- }
- else {
- return false;
- }
- if($timestamp_now > ($timestamp_last_update + $seconds)) {
- $this->update_movie_ratings();
- update_option($this->last_update_option_name, time());
- return true;
- }
- return false;
- }
- /**
- * Loops through all posts, reads their entered IMDb ID
- * and updates and saves the rating.
- *
- * @param array $query
- */
- public function update_movie_ratings(array $query = array()) {
- if(!$query) {
- $query = array(
- "post_type" => "any",
- "showposts" => -1
- );
- }
- $success = false;
- $posts = new WP_Query($query);
- /** Stop if no posts found */
- if(!$posts->have_posts()) {
- return;
- }
- /** Start loop */
- while($posts->have_posts()) {
- $posts->the_post();
- /** Read IMDb ID */
- $imdb_id = get_post_meta(get_the_ID(), "imdb_id", true);
- /** Fetch live rating */
- $rating = imdb_connector_get_movie_detail($imdb_id, "imdbrating");
- /** Update and save rating if found */
- if($rating) {
- $success = update_post_meta(get_the_ID(), "imdb_rating", $rating);
- }
- }
- if($success) {
- update_option($this->last_update_option_name, time());
- }
- }
- /**
- * @param string $order
- *
- * @return \WP_Query
- */
- public function get_movies_by_rating($order = "desc") {
- if(!$this->last_update_timestamp) {
- $this->update_movie_ratings();
- }
- $posts = new WP_Query(
- array(
- "post_type" => "any",
- "orderby" => "meta_value_num",
- "meta_key" => "imdb_rating",
- "order" => $order
- )
- );
- return $posts;
- }
- }
- ?>
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Movies by Rating</title>
- </head>
- <body>
- <?php
- $class = new IMDb_Movies();
- $class->set_update_interval(30, "seconds");
- $movies = $class->get_movies_by_rating();
- if($movies->have_posts()) {
- ?>
- <ol>
- <?php
- while($movies->have_posts()) {
- $movies->the_post();
- ?>
- <li>
- <strong><?php the_title(); ?>:</strong>
- <?php echo get_post_meta(get_the_ID(), "imdb_rating", true); ?>/10
- </li>
- <?php
- }
- ?>
- </ol>
- <?php
- }
- ?>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement