0

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.

  • Have you looked into wp_ update_post and update_post_meta? – birgire Feb 16 at 17:28
  • @birgire these filters won't solve the problem. I think that OP has added a new field (when he already have many posts) and now he want's to automatically modify all of old posts so that they use this new field. But maybe I'm getting it all wrong... – Krzysiek Dróżdż Feb 16 at 21:16
  • thanks @KrzysiekDróżdż, I meant the functions within some loop, but was I was writing on mobile and didn't have time to find the parentheses, sorry about that :-) Hopefully OP can further add what's been tried. – birgire Feb 16 at 21:54
1

OK, so here's the function that should do the trick:

function modify_events_to_use_new_field() {
    $events = get_posts( array(
        'post_type' => 'event',
        'post_status' => 'any',
        'posts_per_page' => -1
    ) );

    foreach ( $events as $event ) {
        if ( preg_match('@^(.*) - ([^-]*)$@', $event->post_title, $matches) ) { 
            // you'll have to modify the POST_META_KEY to the real name of your custom field
            update_post_meta( $event->ID, '<POST_META_KEY>', date('Ymd', strtotime($matches[2]) ) );
        }
    }
}

Now you have to change the name of custom field in there and run that function.

  • I think you're right that only the post meta needs to be updated. I probably misread on my mobile that the date part needed to removed from the title too, so it looks like we don't need wp_insert_post() to update the title as I first thought :-) – birgire Feb 17 at 9:59
  • 1
    I’m not exactly sure if the title should be modified or not. The easier version is to not modify it. And if it has to get changed, then my preg_match allows you to use $matches[1] as a new title and you can set it with wp_update_post :) – Krzysiek Dróżdż Feb 17 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.