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.
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.
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.