Updating post title using wp_update_post

I am creating a custom post type for a people page for a client website that has meta fields for both first and last name, but I would also like to update the title for the custom posts to be a combination of the two (i.e. “firstname lastname”).

I am using wp_update_post to do this but am running into a problem. When I go to update a post, the data is updated correctly, but my cursor spins continuously and the page never reloads. I assume this is because wp_update_post is causing an infinite save_post loop, but the recommended fix for this on the wordpress codex doesn’t seem to be working and I assume there is a problem with how I am calling one or more function.

Here is my code:

add_action('save_post', 'save_details');
add_action('edit_post', 'save_details');

function save_details($post_id){
  global $post;

      if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
              return $post_id;
      }

        update_post_meta($post->ID, "firstname", $_POST["firstname"]);
        update_post_meta($post->ID, "lastname", $_POST["lastname"]);

        if ( ! wp_is_post_revision( $post_id ) ){

            $args = array();
                $args['ID'] = $post_id;
                $args['post_title' ] = implode(' ', array($_POST["firstname"],$_POST["lastname"]));

            remove_action('save_details','save_post');
                wp_update_post( $args );
            add_action('save_details','save_post');
    }

}   

1 Answer
1

the parameters to remove_action are wrong, they should be exactly the same parameters that you used in add_action, first should be the hook and then the function name
remove_action('save_post','save_details');

Leave a Comment