Custom Post Type with Custom Title

I have a custom post type without title support and I’m trying to generate one from post’s taxonomies and custom fields. To do so, I’m using this code:

function custom_post_type_title_filter( $data , $postarr )
    {
      if ($postarr['post_type'] == 'cars'){
            $id = get_the_ID();
            $engine= ', '.get_post_meta($id, 'Engine', true).'l';
            $terms = wp_get_object_terms($id, 'brand');
            $abrand= ' '.$terms[0]->name;
            $amodel = ' '.$terms[1]->name;
            $data['post_title'] = $id.$abrand.$amodel.$engine;
      }
      return $data;
    }
    add_filter( 'wp_insert_post_data' , 'custom_post_type_title_filter' , 99, 2 );

Problem is, to make it work, I have to republish my post. It does not work with new post (it has no ID yet, I guess) and if I change custom field values in post, it won’t generate name from them yet, I’ll have to save it twice to get it done.

Read More

Can someone share a solution with example how it’s done properly?

Also, would be nice to be able to set custom slug too (different from the title).

Related posts

Leave a Reply

2 comments

  1. You can try the following code.

    function custom_post_type_title ( $post_id ) {
        global $wpdb;
        if ( get_post_type( $post_id ) == 'cars' ) {
            $engine= ', '.get_post_meta($post_id, 'Engine', true).'l';
            $terms = wp_get_object_terms($post_id, 'brand');
            $abrand= ' '.$terms[0]->name;
            $amodel = ' '.$terms[1]->name;
            $title = $post_id.$abrand.$amodel.$engine;
            $where = array( 'ID' => $post_id );
            $wpdb->update( $wpdb->posts, array( 'post_title' => $title ), $where );
        }
    }
    add_action( 'save_post', 'custom_post_type_title' );