3

This has been addressed in another post, but the solution was too specific to apply here.

My goal is to use a metabox value (ecpt_name) as the post title so that the user only needs to input their name once, and the name appears in both the admin post listing and online.

As it is now, I require the user to input the post title as the full name AND in a metabox. This allows me to display the fullname online and show the fullname in the admin post listing, but it's double the work.

Looking for something to put into functions.php that hooks the ecpt_name metabox value and places it into the post_title name. thx - Steve

3
<?php
add_action( 'save_post', 'post_updated' );

function post_updated( $post_id ) {

    // verify post is not a revision & not an autosave
    if ( !wp_is_post_revision( $post_id ) && !(defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE) ) {
        // set the new post title
        $post['ID'] = $post_id;
        $post['post_title'] = get_post_meta($post_id, 'ecpt_name', true);

        // update the post, removing the action to prevent an infinite loop
        remove_action( 'save_post', 'post_updated' );
        wp_update_post($post);
        add_action( 'save_post', 'post_updated' );
    }

}
?>
| improve this answer | |
  • 2
    Maybe check for DOING_AUTOSAVE constant being defined too? If not handled by post revision function above? – Adam Oct 18 '12 at 16:06
  • I totally forgot about that, thanks a lot. Updated the code above – Mridul Aggarwal Oct 18 '12 at 18:53
0

Thank you for the reply. Had to clarify that I need this only to affect a certain CPT, not all posts in general. Modified per below. However, the old post title still shows up in the admin post listing. Have to find a solution for that.

// draw post title from name metabox on CPT student

add_action( 'save_post', 'post_updated' );

function post_updated( $post_id ) {

// affect only CPT student
if ($post_type == 'student') {
    // set the new post title
    $post['ID'] = $post_id;
    $post['post_title'] = get_post_meta($post_id, 'ecpt_name', true);

    // update the post, removing the action to prevent an infinite loop
    remove_action( 'save_post', 'post_updated' );
    wp_update_post($post);
    add_action( 'save_post', 'post_updated' );
}

}
| improve this answer | |
  • you should include the wp_is_post_revision & DOING_AUTOSAVE checks as well, as i did in my answer, otherwise you might be updating a revision & not the main post – Mridul Aggarwal Oct 19 '12 at 20:57

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.