Automatically generate custom post title based on meta

I’m working with custom post types to create a custom “product review” type. I’m customizing the UI to have fields for the “Reviewer”, “Product”, and their “Review”. This doesn’t really require a post title though, so I’ve removed that field.

This is all working fine, but when I go to look at all Product Reveiws, the titles are completely unhelpful (Auto Draft, Auto Draft 2, etc.). What I want to do is automatically set the post title to be a combination of the Reviewer’s name and the product they reviewed; something along the lines of “John Smith, Car Radio”.

Read More

I have a function that hooks into the save_post action, and updates the custom meta fields I have set. I figure I need to add something here to accomplish what I’m trying to do, but I’m not sure what function or process this requires.

Thanks in advance!

Related posts

Leave a Reply

1 comment

  1. Jeremy,

    Excellent work not just leaving it at “Auto Draft”. It’s tricky when these types of CPTs don’t have titles. Here is some code I’ve used to accomplish a similar task.

    You’ll need to adjust this for your situation, but it shows you a way to get this done. In particular, you can use the wp_insert_post_data filter to change the title before you add it to the database. Now, one of the biggest mistakes you can make here is filtering ALL post titles. If you are not careful to test for the right context (e.g., when you are saving and/or editing your “product review” CPT, you will find that ALL titles in your site get mangled. My recommendation is to make use of nonce fields in your meta boxes to detect when the right form is submitted.

    Here’s my code:

    add_filter('wp_insert_post_data', 'change_title', 99, 2);
    
    function change_title($data, $postarr)
    {    
        // If it is our form has not been submitted, so we dont want to do anything
        if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
    
        // Verify this came from the our screen and with proper authorization because save_post can be triggered at other times
        if(!isset($_POST['my_nonce_field'])) return;
    
        // If nonce is set, verify it
        if(isset($_POST['my_nonce_field']) && !wp_verify_nonce($_POST['my_nonce_field'], plugins_url(__FILE__))) return;
    
        // Get the associated term name
        foreach($_POST['tax_input']['complaint-type'] as $term) {$term_id = $term;}
    
        // Get name of term
        $term = get_term_by('id', $term_id, 'complaint-type');
    
        // Combine address with term
        $title = $_POST['address']['address1'].' ('.$term->name.')';
        $data['post_title'] = $title;
    
        return $data;
    }
    

    Don’t get caught up in my manipulations of the title. Just realize that you need to set $data['post_title'] and return $data.