2015-09-25 5 views
2

Я создаю сообщение типа «участник». И у меня есть API сотрудников компании. Из этого API я беру информацию о персонале «ID», «день», «start_work» и «finish_work». Каждый день новые данные, потому что у каждого из сотрудников нет нормального графика рабочего времени, они работают, когда хотят. Таким образом, данные всегда различаются. В этом типе сообщения я создаю это 3 метафила, где я добавляю только «ID». «start_work» и «finish_work» автоматически анализируются из API и добавляются в эти поля. Эти данные каждый день меняются и меняются в моем метафолине тоже, но он не сохраняет эти данные в базе данных автоматически. Он изменяется только при редактировании страницы в панели администратора.Как автоматически обновлять данные в Wordpress?

<?php 
     function add_member_post_type1_meta_box() { 
     add_meta_box(
      'member_post_type1_meta_box', 
      'Today Working hours', 
      'show_member_post_type1_meta_box', 
      'member', 
      'normal', 
      'high' 
     ); 

    } 

    add_action('add_meta_boxes', 'add_member_post_type1_meta_box'); 

    function user_worker($user_id) { 
     global $user_today, $work_today, $break_today, $member_post_type1_meta_fields; 
     $ch = curl_init(); 
     curl_setopt($ch, CURLOPT_URL, "API_DOMAIN"); 
     curl_setopt($ch, CURLOPT_HEADER, false); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     $result = curl_exec($ch); 
     curl_close($ch); 

    //convert json to array 
     $worker_shifts = json_decode($result, true); 

    //set correct timezone for date functions 
     date_default_timezone_set("Europe/Helsinki"); 

    //get current hour 
     $current_hour = date("G"); 

     $ID = $user_id; 
     $user_today = array(); 
     $work_today = false; 
     foreach($worker_shifts as $worker) { 
      if (in_array($ID, $worker)) { 
       $user_today = $worker; 
       $work_today = true; 
      } 
     } 
     $break_today = sizeof($user_today["shifts"])-1; 
     if ($break_today>0) { 
      array_push($member_post_type1_meta_fields, 
       array(
        'label'=> 'Break', 
        'id' => 'custom_break', 
        'type' => 'break' 
       ) 
      ); 
      for ($i=0;$i<$break_today;$i++) { 
       array_push($member_post_type1_meta_fields, 
        array(
         'label'=> 'Start work day at', 
         'id' => 'custom_start_'.$i, 
         'type' => 'start_'.$i 
        ), 
        array(
         'label'=> 'Finish work day at', 
         'id' => 'custom_finish_'.$i, 
         'type' => 'finish_'.$i 
        ) 
       ); 
      } 
     } 
    } 

    // Field Array 
    $prefix = 'custom_'; 
    $member_post_type1_meta_fields = array(
     array(
      'label'=> 'Day', 
      'id' => $prefix.'day', 
      'type' => 'day' 
     ), 
     array(
      'label'=> 'Start work day at', 
      'id' => $prefix.'start', 
      'type' => 'start' 
     ), 
     array(
      'label'=> 'Finish work day at', 
      'id' => $prefix.'finish', 
      'type' => 'finish' 
     ), 
    ); 

    // The Callback 
    function show_member_post_type1_meta_box() { 
     global $member_post_type1_meta_fields, $user_id, $post, $user_today, $work_today, $break_today, $wpdb; 
     user_worker($user_id); 
    // Use nonce for verification 
     echo '<input type="hidden" name="custom_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />'; 

    // Begin the field table and loop 
     echo '<table class="form-table">'; 
     foreach ($member_post_type1_meta_fields as $field) { 
      // get value of this field if it exists for this post 
      $meta = get_post_meta($post->ID, $field['id'], true); 
      // begin a table row with 
      echo '<tr> 
      <th><label for="'.$field['id'].'">'.$field['label'].'</label></th> 
      <td>'; 
      if ($work_today) { 

       switch($field['type']) { 
        // case items will go here 
        case 'day': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$user_today["date"].'" style="width: 100%; height: 40px;" /> 
       <br />'; 
         update_post_meta($post->ID, $field['id'], $user_today["date"]); 
         break; 
        case 'break': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$break_today.'" style="width: 100%; height: 40px;" /> 
       <br />'; 
         update_post_meta($post->ID, $field['id'], $break_today); 
         break; 
        case 'start': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.intval($user_today["shifts"][0][0]).'" style="width: 100%; height: 40px;" /> 
       <br />'; 
         update_post_meta($post->ID, $field['id'], intval($user_today["shifts"][0][0])); 
         break; 
        case 'finish': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.intval($user_today["shifts"][0][1]).'" style="width: 100%; height: 40px;" /> 
       <br />'; 
         update_post_meta($post->ID, $field['id'], intval($user_today["shifts"][0][1])); 
         break; 
       } //end switch 
       $wpdb->update('r4j47_postmeta', 
        array('custom_day' => $user_today["date"], 'custom_break' => $break_today, 'custom_start' => intval($user_today["shifts"][0][0]), 'custom_finish' => intval($user_today["shifts"][0][1])), 
        array('post_id' => $post->ID), 
        array('%s', '%d', '%d', '%d'), 
        array('%d') 
       ); 
       if ($break_today>0) { 
        for ($i=0;$i<$break_today;$i++) { 
         if ($field['type']=='start_'.$i) { 
          echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.intval($user_today["shifts"][$i+1][0]).'" style="width: 100%; height: 40px;" /> 
         <br />'; 
          update_post_meta($post->ID, $field['id'], intval($user_today["shifts"][$i+1][0])); 
         } 
         if ($field['type']=='finish_'.$i) { 
          echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.intval($user_today["shifts"][$i+1][1]).'" style="width: 100%; height: 40px;" /> 
         <br />'; 
          update_post_meta($post->ID, $field['id'], intval($user_today["shifts"][$i+1][1])); 
         } 
         $wpdb->update('r4j47_postmeta', 
          array('custom_start_'.$i => intval($user_today["shifts"][$i+1][0]), 'custom_finish_'.$i => intval($user_today["shifts"][$i+1][1])), 
          array('post_id' => $post->ID), 
          array('%d', '%d'), 
          array('%d') 
         ); 
        } 
       } 
      } else { 
       switch($field['type']) { 
        // case items will go here 
        case 'day': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="" style="width: 100%; height: 40px;" /> 
       <br />'; 
         delete_post_meta($post->ID, $field['id']); 
         break; 
        case 'start': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="" style="width: 100%; height: 40px;" /> 
       <br />'; 
         delete_post_meta($post->ID, $field['id']); 
         break; 
        case 'finish': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="" style="width: 100%; height: 40px;" /> 
       <br />'; 
         delete_post_meta($post->ID, $field['id']); 
         break; 
        case 'break': 
         echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="" style="width: 100%; height: 40px;" /> 
       <br />'; 
         delete_post_meta($post->ID, $field['id']); 
         break; 
       } //end switch 
       $wpdb->update('r4j47_postmeta', 
        array('custom_day' => '', 'custom_break' => '', 'custom_start' => '', 'custom_finish' => '', 'custom_start_0' => '', 'custom_finish_0' => ''), 
        array('post_id' => $post->ID), 
        array('%s', '%d', '%d', '%d', '%d', '%d'), 
        array('%d') 
       ); 
      } 
      echo '</td></tr>'; 
     } // end foreach 
     echo '</table>'; // end table 
    } 

    // Save the Data 
    function save_member_post_type1_meta($post_id) { 
     global $member_post_type1_meta_fields; 

    // verify nonce 
     if (!wp_verify_nonce($_POST['custom_meta_box_nonce'], basename(__FILE__))) 
      return $post_id; 
    // check autosave 
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) 
      return $post_id; 
    // check permissions 
     if ('page' == $_POST['post_type']) { 
      if (!current_user_can('edit_page', $post_id)) 
       return $post_id; 
     } elseif (!current_user_can('edit_post', $post_id)) { 
      return $post_id; 
     } 

    // loop through fields and save the data 
     foreach ($member_post_type1_meta_fields as $field) { 
      $old = get_post_meta($post_id, $field['id'], true); 
      $new = $_POST[$field['id']]; 
      if ($new && $new != $old) { 
       update_post_meta($post_id, $field['id'], $new); 
      } elseif ('' == $new && $old) { 
       delete_post_meta($post_id, $field['id'], $old); 
      } 
     } 
// end foreach 
    } 
    add_action('save_post', 'save_member_post_type1_meta'); 
?> 

ответ

0

Вы можете запустить wp-cron для выполнения чего-либо автоматически и в указанное время или на регулярном интервале.

//If your code is in plugin, On plugin activation 
register_activation_hook(__FILE__, 'schedule_time'); 

//Or use init action instead of register_activation_hook, Add function to register event to WordPress init 
add_action('init', 'schedule_time'); 

function schedule_time() { 
//Schedule on daily basis 
    wp_schedule_event(time(), 'daily', 'your_main_function_call'); 
} 

function your_main_function_call() { 
    // this will execute daily 
} 
1

Я думаю, вам нужно создать задание cron и установить его как время на сервере. Это лучший способ автоматического обновления. wp_schedule_event() не работает какое-то время в соответствии с нашим требованием.

Смежные вопросы