wordpressposttitleautogenerate

auto generate post title in wordpress like ABC-123456


I want to auto-generate post title like that Ex : ABC-123456 also i need to let (( ABC- )) fixed and random change the 06 numbers and to dont change the post title through updating the post


Solution

  • First, to modify WordPress behavior the correct way, you find an appropriate hook. In this case, that would be a filter that allows changing the Post data before it is saved to the db.

    The filter 'wp_insert_post_data' is exactly what you need, so you add your filter, and connect it to a function like so:

    function zozson_filter_post_title(){
    }
    add_filter( 'wp_insert_post_data', 'zozson_filter_post_title',50,4);
    

    'wp_insert_post_data' is the name of the filter

    'zozson_filter_post_title' is the name you give to your function, to hook to it.

    50 is the priority. I chose 50 to run it after most other things. Default is 10

    4 is the number of variables that the filter passes to your function.

    So now we will add those variables and the logic inside it, to assign these CPT sho7nat those titles on admin saving them.

    function zozson_filter_post_title( $data, $postarr, $unsanitized_postarr, $update){
    
       //Then if it is the post type sho7nat
       if( $data['post_type'] !== 'sho7nat' ){
           return $data;
        }
    
        //If there is already a titled saved ($update returns true always)
       if( $data['post_title'] !== '' ){
           return $data;
        }
    
        //Let's build our title
        $post_title = ' ABC-';
       
        //What better random number that a unique timestamp?
        $random_number = strtotime('now');
    
        //Add the random number to the post title to save. You can do these in 1 line instead of 3
        $post_title.= $random_number;
       
        
         //We now have a post title with ABC- fixed and a random number, tell WordPress to use it as the post title
         $data['post_title'] = $post_title;
    
          return $data;
    
    }
    add_filter( 'wp_insert_post_data', 'zozson_filter_post_title',50,4);
    

    The title automatically assigned should be like in this example: enter image description here