0

I have a Custom Post Type with the slug of "sightings".

I do not need a post title, so I have removed the functionality - but now the posts are being saved as (no-title).

I read about the save_post functionality that can change the post title to something upon save? I hope thats correct.

Can someone help me write some code to achieve this? I have googled it, yes and also tried a couple of Stack Exchange snippets, but they dont seem to do anything.

Rob.

1

1 Answer 1

0

A very easy way to accomplish this would be to add something like this into your themes functions.php file:

function update_post(int $id, \WP_Post $post, bool $update) 
{
  // Case the post object to an array
  $data = (array) $post;
  // Set the title to the ID of the post
  $data['post_title'] = $id;
  // We need to remove the action to prevent an infinite loop
  remove_action('save_post', 'update_post');
  wp_update_post($data);
  // Finally re-add the action hook
  add_action('save_post', 'update_post', 10, 3);
}
add_action('save_post', 'update_post', 10, 3);

Notice that you can narrow down which post types to handle by using add_action('save_post_{$post->post_type}', 'update_post', 10, 3);. So if you custom post type is called video then you would add the hook like this:

add_action('save_post_video', 'update_post', 10, 3);

Read more in the documentation:

2
  • Thanks, ill give this a go!! :) Commented Feb 10, 2023 at 15:02
  • I cant seem to get this working, the page just times out when clicking Publish or Update. My Custom Post Type is called "sightings". Can you help? I have tried add_action('save_post_sightings', 'update_post', 10, 3); Commented Feb 15, 2023 at 14:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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