How can I automatically insert the page content as the title?

I have a custom post type with no Title field. These are short status messages, where only the content matters. The RSS feed and permalink display the title as Auto Draft, which is not very useful. Ideally, it would have the post content, or at least the first 10 or so words.

I’ve tried this function, but it still appears as Auto Draft:

add_filter('title_save_pre', 'save_title');
function save_title($my_post_title) {
        if ($_POST['post_type'] == 'servicestatus') :
          $new_title = wp_trim_words( $_POST['content'], $num_words = 10, $more = null )
          $my_post_title = $new_title;
        endif;
        return $my_post_title;
}

add_filter('name_save_pre', 'save_name');
function save_name($my_post_name) {
        if ($_POST['post_type'] == 'servicestatus') :
          $new_name = wp_trim_words( $_POST['content'], $num_words = 10, $more = null )
          $my_post_name = $new_name;
        endif;
        return $my_post_name;
}

Related posts

Leave a Reply

1 comment

  1. I think save_post action hook is the proper one. Maybe you’ll want to insert some checking if the post title is already set ($post_object->post_title), as this code always update the title according to the content.

    add_action( 'save_post', 'save_post_wpse_87921', 10, 2 );
    
    function save_post_wpse_87921( $post_id, $post_object ) 
    {
        // Auto save?
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )  
            return;
    
        // Correct post_type
        if ( 'servicestatus' != $post_object->post_type )
            return;
    
        $new_title = wp_trim_words( $post_object->post_content, $num_words = 10, $more = '' );
    
        // Unhook this function so it doesn't loop infinitely
        remove_action( 'save_post', 'save_post_wpse_87921' );
    
        // Call wp_update_post update, which calls save_post again. 
        wp_update_post( array( 
            'ID' => $post_id,
            'post_title' => $new_title
        ));
    
        add_action( 'save_post', 'save_post_wpse_87921', 10, 2 );
    }