Auto Generate Post Title in WordPress

By default users or authors need to add the Post title in WordPress before publishing the post or page. However, it can also be generated automatically in many different ways. Usage and scope of such feature is highly dependent on number of key factors and the overall requirements of the project.

Recently, I was working on a site where I was required to make a form for the registered users (different role) to be able to submit orders from the front-end. I was able to get this job done using CPT and Post Meta Box. The problem was I didn't want the users to type their own "Title" for the post as it wasn't necessary. I thought of generating the post title automatically based on the post ID with a prefix. This method can particularly be useful for repetitive submissions.

This is exactly where the following snippet was highly useful.

function auto_generate_post_title($title) {
   global $post;
   if (isset($post->ID)) {
      if (empty($_POST['post_title']) && 'post' == get_post_type($post->ID)){
         // get the current post ID number
         $id = get_the_ID();
         // add ID number with order strong
         $title = 'Prefix-'.$id;} }
   return $title; 

The snippet above will generate the post title upon saving/submitting the form from the front-end. It would look something like "Prefix-xxx" (xxx to be the Post ID number). You can change the prefix with whatever you want. Since in my case it was an order, I used the "Order" word instead of "Prefix" and that gave me a clear-cut title like "Order-12" and things of that sort.

What's Going on?

The idea is fairly simple. We wrote a function that would only be called when the post title is being saved into the database. Instead of user's input, I am taking the post ID and a prefix to pass it as the user input or post title. This is as simple as it can get.

How to Use this Snippet?

Please do not forget that I used this snippet for a custom post type instead of regular "post" of WordPress. If you want to use this snippet for your registered custom post type, simply change the post type on 6th line of the snippet (get_post_type value). Another interesting issue can be changing the post ID with other numerical values. In this case, you can also use time to be your unique identifier for your title. It entirely depends on your own requirement but you have the absolute freedom to get creative with this snippet.

Feel free to play around with this snippet and let me know if you have any question on this topic from the comment section below. Now, make something great with WordPress.


Commenting is disabled.