Support

Account

Home Forums Backend Issues (wp-admin) Batch Extract Date from post title and put into ACF custom field

Helping

Batch Extract Date from post title and put into ACF custom field

  • I have a custom post type called ‘events’ with around 700 posts, the titles are consistently formatted like this:

    Event Title – January 1st 2019

    I need to isolate the date in another field. I am using Advanced custom fields and have added a date field to the events custom post type.

    I need to write a script to extract the date from each title and insert it into the custom field.

    How would I do this? I have tried writing SQL statements but just cant get it to work. I need some guidance.

  • You would need to create a function that runs on the site when the page loads. It could very likely time out the site do to the number of posts you’re dealing with but that can be worked around.

    Some of this is guess work and you’ll need to test and make adjustments

    
    add_action('init', 'convert_title_to_date'); // run it on site init
    function convert_title_to_date() {
      // do a query to get all of the events posts
      $args = array(
        'post_type' => 'events',
        'posts_per_page' => -1,
        // meta query to not get posts
        // where the date field is already set
        'meta_query' => array (
          array(
            // replace key with the name of your date field
            'key' => 'MY_DATE_FIELD',
            'compare' => 'NOT EXISTS'
          )
        )
      );
      $query = new WP_Query($args);
      if (count($query->posts)) {
        foreach ($query->posts as $post) {
          $title = get_the_title($post->ID);
          $date = substr($title, strrpos($title, '-')+2);
          $date = date('Ymd', strtotime($date));
          // use the field key to update
          // because the field does not exist
          // replace w/your field key
          update_field('field_1234567', $date, $post->ID);
        }
      }
    }
    

    Like I said, the first time this runs it may time out because of the number of queries. That’s what the meta query is for. Each time you run this it will only get posts where the field has not been updated yet so eventually after loading the page several time it will get through all of them.

Viewing 2 posts - 1 through 2 (of 2 total)

The topic ‘Batch Extract Date from post title and put into ACF custom field’ is closed to new replies.