Created
May 30, 2024 07:51
-
-
Save raftaar1191/8d70eadc02036d021c4d368bb05815eb to your computer and use it in GitHub Desktop.
Generate the post slug for the draft testimonial (CPT) as well
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
/** | |
* Generate the post slug for the draft post as well | |
* | |
* @param int $post_id Post ID. | |
* @param WP_Post $post Post object. | |
* @param bool $update Whether this is an existing post being updated. | |
**/ | |
function lubus_generate_slug_for_draft_post( $post_id, $post, $update ) { | |
// If the post is a draft and has no slug. | |
if ( | |
'draft' === $post->post_status | |
&& | |
( empty( $post->post_name ) | |
|| 'auto-draft' == $post->post_name ) | |
) { | |
// Generate a slug from the post title. | |
$slug = sanitize_title( $post->post_title ); | |
// Remove the action to avoid infinite loop. | |
remove_action( 'save_post', 'lubus_generate_slug_for_draft_post', 10000 ); | |
// Update the post with the new slug. | |
wp_update_post( | |
array( | |
'ID' => $post_id, | |
'post_name' => $slug, | |
) | |
); | |
// Re-add the action. | |
add_action( 'save_post', 'lubus_generate_slug_for_draft_post', 10000, 3 ); | |
} | |
} | |
add_action( 'save_post_testimonial', 'lubus_generate_slug_for_draft_post', 10000, 3 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment