WordPress.org

Forums

[resolved] Modifying Title Before Saving Custom Post (2 posts)

  1. cacheflowdesign
    Member
    Posted 3 years ago #

    I'm trying to find an efficient way to modify both the title and slug of custom post type. I would like to systematically generate a title based on a custom meta data value and the post id. Both the title would be something like {metadata-value}-{post-id}. For this custom post type, I don't want my user to be able to set the title so I've disabled it on the 'Edit Post' screen.

    Modifying the title dynamically seems to be very tricky and searching for help has yielded few results. My first instinct was to hook into the save_post action, but I don't know how to set the title once I'm there. I'd prefer not to create a custom meta data field like 'custom-title', I'd like to modify the actual title prior to saving if possible.

    Any ideas?

  2. cacheflowdesign
    Member
    Posted 3 years ago #

    Found it!

    I used the filter wp_insert_post_data, checked to make sure it was my custom post type, then set the title. The filter executes just before inserting data into the database, so I was good to go.

    add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );
    
    function modify_post_title( $data , $postarr )
    {
      if($data['post_type'] == '{custom post type}') {
        $data['post_title'] = 'New Title';
      }
      return $data;
    }

    I pulled the code from http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data, I don't know what the '99' and 2 parms are in the call to add_filter, but it works.

Topic Closed

This topic has been closed to new replies.

About this Topic