I've read here and other places about setting a post's title based on it's metadata. Unfortunately I'm unable to get it working and I'm hoping someone else can point me in the proper direction or explain where I'm wrong. Here's my code:

function setup_match_title( $data, $postarr ) {
    if ( $data['post_type'] == 'matches' && $data['post_title'] == '' ) :

        $a = get_the_title( get_post_meta( $postarr['ID'], 'away_name', true ) );
        $h = get_the_title( get_post_meta( $postarr['ID'], 'home_name', true ) );

        $data['post_title'] = $a . ' vs ' . $h;


    return $data;

add_filter( 'wp_insert_post_data', 'setup_match_title', 99, 2 );

The home and away team metaboxes are select boxes populated with a list of "teams" post_type that stores the team's post_id.

When I publish a new "match", my post title reads "Auto draft vs Auto draft". My guess is since nothing is in the database when get_post_meta() runs, it returns Auto Draft. I believe that because if I go back into the post, empty the title (so it passes the initial if statement) and Update it, the proper title is set.

What am I doing wrong? Is there any way to get the value of a select box at runtime using get_post_meta()?


As soon as you hit "Add New" and the new post pages starts to load, WordPress inserts a mostly blank post template into the database. Periodically after that you get auto-saves. You don't want either. You will need to add additional conditions to prevent your code from running in those circumstances. Something like this in addition to your $data['post_type'] == 'matches' && $data['post_title'] == '':

if (
  || (defined('DOING_AJAX') && DOING_AJAX)
  || ($p->post_status === 'auto-draft')
) {

Personally, I think you'd be better off hooking into a different, more specialize hook, like publish_post or a post status transition hook.

  • It only adds the "auto draft" after the post is published for the first time (I apologize for the confusion -- I've updated that aspect of the original question). I did add the code you suggested and it doesn't affect what happens. – JohnG May 6 '14 at 17:56

For whatever reason get_post_meta() wasn't working when run inside the wp_insert_post_data() filter. However, after doing a var_dump( $postarr ) I saw that the meta keys were being populated with the expected values.

I simply replaced the get_post_meta() function lines w/ the following:

$a = isset( $postarr['away_name'] ) ? get_the_title( $postarr['away_name'] ) : '';
$h = isset( $postarr['home_name'] ) ? get_the_title( $postarr['home_name'] ) : '';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.