Automatically generate custom post title based on meta

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.

Leave a Comment