This question is relate to another one on WPSE: Set post title from two meta fields

I am looking for a way to define a WP custom post type's title and slug from a custom field (i.e. first name and last name). Such that if I enter "John" in the fname field and "Doe" in the lname field, the title would be "John Doe" and the slug would be "john-doe".

The solution offered on thread linked above works but it requires that I "save draft" first before I hit "publish". If I click on "publish" right away, the post title is nothing but a single dash/hyphen "-" and the slug is the post ID.

Anyone know how to make it work without the need to "save draft" first?

--- Update --- Here's the code I'm using. It's based on the linked thread above.

function my_set_empname_title( $data , $postarr ) {
    if($data['post_type'] == 'employees') {
        $emp_fname = get_post_meta($postarr['ID'], 'emp_first_name', true);
        $emp_lname = get_post_meta($postarr['ID'], 'emp_last_name', true);
        $new_title = "$emp_fname" . '-' . "$emp_lname";
        $post_slug = sanitize_title_with_dashes($new_title, '', $context = 'save');
        $post_slugsan = sanitize_title($post_slug);
        $data['post_title'] = $new_title;
        $data['post_name'] = $post_slugsan;
    return $data;
add_filter( 'wp_insert_post_data' , 'my_set_empname_title' , '99', 2 );
  • The solution in the linked question does not require me to post a draft first. Please explain your question more thoroughly and explain how it is not a duplicate of the linked question. – s_ha_dum Mar 15 '14 at 16:55
  • 1
    Can you post the code you are using? Maybe the issue is somewhere else in your code. – czerspalace Mar 15 '14 at 17:40
  • @czerspalace I updated my original post with the code. – delpino Mar 16 '14 at 7:47
  • @s_ha_dum As I've explained in the original post above, I am unable to get the desired results without doing a "save draft" first. I've included the code I'm using. With regard to the similarity with the linked question - I tried posting a follow-up to that thread (by commenting) but I kept getting the "you need to have a reputation of 50" or something like that. I also got the suggestion to post a new question - which is what I did. – delpino Mar 16 '14 at 7:51
  • You can't get_post_meta from a post that doesn't exist yet. You have to get the first and last name using their form field names. – czerspalace Mar 17 '14 at 2:08

Try replacing

 $emp_fname = get_post_meta($postarr['ID'], 'emp_first_name', true);
 $emp_lname = get_post_meta($postarr['ID'], 'emp_last_name', true);


$emp_fname = $_POST['emp_first_name'];
$emp_lname = $_POST['emp_last_name'];

Replace the $_POST array keys with whatever the field name is on your form

| improve this answer | |

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.