Created
January 2, 2017 15:16
-
-
Save ErikBernskiold/7564aa9cbc8981675873f1b4c0a72f24 to your computer and use it in GitHub Desktop.
Sometimes we want to dynamically generate the post title of a custom post type from data entered in other fields, without the user seeing the title in the editing screen.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| add_action( 'save_post', 'set_cpt_post_title' ); | |
| function set_cpt_post_title( $post_id, $post ) { | |
| // Don't change title for revisions. | |
| if ( wp_is_post_revision( $post_id ) ) { | |
| return; | |
| } | |
| // Get the current post type. | |
| $post_type = get_post_type( $post ); | |
| // If this isn't a 'MY_POST_TYPE_KEY' post, don't update the title. | |
| if ( 'MY_POST_TYPE_KEY' !== $post_type ) { | |
| return; | |
| } | |
| // Get the data here. | |
| // Create the title. | |
| $title = ''; | |
| // Unhook this function so we don't loop indefinitely. | |
| remove_action( 'save_post', array( $this, 'set_cpt_post_title' ) ); | |
| // Update our title. | |
| wp_update_post( array( | |
| 'ID' => $post_id, | |
| 'post_title' => $title, | |
| ) ); | |
| // Re-hook this function, since we are done. | |
| add_action( 'save_post', array( $this, 'set_cpt_post_title' ) ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment