(WordPress) Generate post title from custom field

By | April 14, 2016

I had a custom post type that only used custom fields, so I needed to generate a post title from there.
Here’s one way. You can if course chain as many if else as you want to check other types.


function custom_post_type_title($post_id)
    global $wpdb;
    if (get_post_type($post_id) == 'staff') {
        $name = get_post_custom_values('name');
        $title = $name[0];
        $where = array('ID' => $post_id);
        $wpdb->update($wpdb->posts, array('post_title' => $title), $where);

add_action('save_post', 'custom_post_type_title');

3 thoughts on “(WordPress) Generate post title from custom field

  1. John

    Is this supposed to overwrite the blank post_title in the database? It doesn’t seem to work for me. My issue is that I am trying to use post relationships between one cpt to another. But the dropdown that shows post relationships shows blank options because it pulls the post_title from the database.

    1. John

      Oh I see, it only applies if it is an update and not an initial publish. Is there a way to make this happen when a post is published, as opposed to updated?

      1. Christoffer Wadensten Post author

        This should actually work when publishing. Don’t know about your particular case, but if I remember correctly I just call this function (passing the post id) when a post is created.


Leave a Reply

Your email address will not be published. Required fields are marked *