Search code examples
phpwordpressadvanced-custom-fields

How to auto update acf field based on posting date?


I have a custom post called Project.
I need to automatically update a field with 100 when the post date is over 7 days.
I tried the following coed in function.php but it doesn’t auto update the field.
Would you please let me know how to fix the code?

function update_active_based_on_date() {
  // query to get all custom posts - project 
  $args = array(
    'post_type'      => 'project',
    'posts_per_page' => -1
  );
  $query = new WP_Query($args);

  // if posts are returned and more than 7days, update infosubmit field
  if ($query->have_posts()) {
  global $post;
  $timestamp = get_the_time( 'U', $post->ID );
  $diff = current_time('timestamp') - $timestamp;
    while ($query->have_posts()  &&  $diff > 604800) {
      $query->the_post();
      $field_key = "field_60836f942ae12";
      $value = "100";
      update_field($field_key, $value, $post->ID);
    } // end while have_posts
    wp_reset_postdata();
  } // end if have_posts
} // end function

Thank you.


Solution

  • You can achieve this like:

    function update_active_based_on_date() {
        // query to get all custom posts - project
        $args = array(
            'post_type'      => 'project',
            'posts_per_page' => -1
        );
        $query = new WP_Query($args);
    
        if ($query->have_posts()) {
            global $post;
            while ($query->have_posts()) {
                $query->the_post();
                // if posts are returned and more than 7days, update infosubmit field
                $diff = time() - strtotime(get_the_date());
                if($diff > 604800){
                    $field_key = "field_60836f942ae12";
                    $value = "100";
                    update_field($field_key, $value, $post->ID);
                }
            } // end while have_posts
            wp_reset_postdata();
        } // end if have_posts
    } // end function
    
    add_action('init','update_active_based_on_date');