0

I have a custom post type with some meta boxes added to the post type. The code for the CPT meta boxes works fine. I then added the following code to use the meta boxes as the title of the post. The problem is that the code works for all posts, pages and other CPT on the site.

Could someone please advise on how to change below code to just work for the CPT it is attended to be used for.

////////////////////////////////////////////////////////////////////
// Set post title //
////////////////////////////////////////////////////////////////////   
add_action( 'save_post', 'post_updated' );
function post_updated( $post_id ) {
$meta_box_one       = get_post_meta(get_the_ID(), 'meta_box_one', true);
$meta_box_two       = get_post_meta(get_the_ID(), 'meta_box_two', true);
$meta_bax_three     = get_post_meta(get_the_ID(), 'meta_bax_three', true);
$post_name  = '' . $meta_box_one . ' ' . $meta_box_two  . ' ' . 
$meta_box_three . '';

   // 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'] =  $post_name; 

    // 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' );
}
}
0

You can use get_post_type to check type:

function post_updated( $post_id ) {
    $post_type = get_post_type($post_id);
    // If this isn't a 'book' post, don't update it.
    if ( "book" != $post_type ) return;

    // the rest of your code...
}

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.