简体   繁体   中英

Update WordPress post meta without refreshing the page

I want to update post meta without refreshing the page:
I have this part of code:

$api = "https://api.themoviedb.org/3/tv/1402?api_key=########";
$json = file_get_contents($api);
$data = json_decode($json, TRUE);
update_post_meta($post->ID, 'status', $data['status']);

I write this code in post template. which by visiting this page post meta will be update. I want a way to update post meta automatically without refreshing or visiting the page page.

Have you checked the wp-cron ? Your could create a schedule event that is fired every day or every 12hours...?

In this function you could query your posts an loop through each post to update the post meta.

It could be something like this:

<?php

if ( ! wp_next_scheduled( 'al_my_scheduled_task' ) ) {
  wp_schedule_event( time(), 'hourly', 'al_my_scheduled_task' );
}

add_action( 'al_my_scheduled_task', 'al_my_scheduled_function' );

function al_my_scheduled_function() {

  $args = array(
    'post_type' => 'posts',
    'posts_per_page' => -1,
    'limit' => -1
  )
  $posts = get_posts($args);

  if($posts){
    foreach($posts as $post){ setup_postdata($post);
      $api = "https://api.themoviedb.org/3/tv/1402?api_key=########";
      $json = file_get_contents($api);
      $data = json_decode($json, TRUE);
      update_post_meta( get_the_id() , 'status', $data['status']);
    }
    wp_reset_postdata();
  }

}

?>

this code is not tested! Plz test it yourself.

Please take a look at this answer concerning problems with wp-cron and caching plugins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM