Created
March 26, 2022 00:05
-
-
Save swinggraphics/343c6f8635fc798350d35e3f694c5dcb to your computer and use it in GitHub Desktop.
Set CPT slug by default based on taxonomy and post_parent
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
/** | |
* Default event recap slug | |
* If has parent and is in category Recap, set slug to "recap". | |
* Can't use `wp_insert_post_data` because taxonomy data isn't included, frustratingly. | |
*/ | |
// Catch changes in block editor | |
add_filter( 'rest_post_dispatch', 'recap_slug_rest', 10, 3 ); | |
function recap_slug_rest( $result, $server, $request ) { | |
if ( 'PUT' == $request->get_method() ) { | |
$post_id = $request->get_param( 'id' ); | |
$post = get_post( $post_id ); | |
if ( 'event' == $post->post_type && $post->post_parent ) { | |
$terms = get_the_terms( $post_id, 'event_category' ); | |
foreach ( $terms as $term ) { | |
if ( in_array( $term->slug, [ 'recap', 'recaps' ] ) ) { | |
wp_update_post( [ 'ID' => $post_id, 'post_name' => 'recap' ] ); | |
break; | |
} | |
} | |
} | |
} | |
return $result; | |
} | |
// Catch quick/bulk edit | |
add_action( 'save_post_event', 'default_recap_slug_save_post', 10, 3 ); | |
function default_recap_slug_save_post( $post_ID, $post, $update ) { | |
if ( defined( 'REST_REQUEST' ) ) return; | |
if ( $post->post_parent ) { | |
$terms = get_the_terms( $post, 'event_category' ); | |
foreach ( $terms as $term ) { | |
if ( in_array( $term->slug, [ 'recap', 'recaps' ] ) ) { | |
remove_action( 'save_post_event', 'default_recap_slug_save_post' ); | |
wp_update_post( [ 'ID' => $post->ID, 'post_name' => 'recap' ] ); | |
add_action( 'save_post_event', 'default_recap_slug_save_post', 10, 3 ); | |
break; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment