I'm trying to auto generate the post title and slug for a custom post type upon post creation.
It's sort of a log book, the users will only write in the main content field.
The title and slug both consist of the creation date and author name.
For example:
2019-11-15 - Doe, John
This is the code:
<?php
function auto_generate_title_on_save_post( $post_id ) {
if ( ! wp_is_post_revision( $post_id ) ) {
// Avoid the infinite loop.
remove_action( 'save_post', 'auto_generate_title_on_save_post' );
if ( get_post_type( $post_id ) === 'custom_post_type' ) { // Check and update for the specific $post_type.
// Get current user and current date.
$current_user = wp_get_current_user();
$post_creation_date = get_the_date( 'Y-m-d' );
$my_post = array(
'ID' => $post_id,
'post_name' => $post_creation_date . ' - ' . $current_user->user_lastname . ', ' . $current_user->user_firstname, // Construct post_slug.
'post_title' => $post_creation_date . ' - ' . $current_user->user_lastname . ', ' . $current_user->user_firstname, // Construct post_title.
);
write_log(array( 'ID' => $post_ID));
// Update the post into the database.
wp_update_post( $my_post, true );
add_action( 'save_post', 'auto_generate_title_on_save_post' );
}
}
}
add_action( 'save_post', 'auto_generate_title_on_save_post' );
?>
Everything works fine when the custom post type has REST disabled.
When I enable 'show_in_rest' the date is missing and the following error appears:
Updating failed. Error message: The response is not a valid JSON response.
However the post and title do get updated, but as already said the date is missing:
- Doe, John
Do I have to format the date differently or use another function to make it work with the REST API?