Dynamically Set WordPress Post Title To The Category Name

Q: Is it possible to set the post title upon saving the post to be the assigned category name?

A: Yes it is.

Each time a post is saved or created, a filter is called. You can hook into that filter and set the title of the post to the value you want. This will, in contrast to a solution with jQuery, ensure that your data is correct regardless how the editor configured his browser or if something is broken on his system.

If you want to find out more about the hooks I’m talking about, these two functions are a good place to start: wp_update_post() and wp_insert_post(). The related source-code is available in /wp-includes/post.php. You can find all associated hooks inside the functions code.

There are multiple available, so I can only suggest one at best guess. That would be wp_insert_post_data in line 2 531, you can change/set the title by hooking into that filter:

add_filter('wp_insert_post_data', function($data, $postarr) {
    /* your job */
    $data['post_title'] = $defaultTitle;
    $return $data;
}, 10, 2);

Or it’s possible even better to hook into save_post action in line 2 620 as it’s already saved within the database and might work for both functions. The principle is the same: You modify the data on your own.

Leave a Comment