Skip to content

Instantly share code, notes, and snippets.

@5ally
Created May 14, 2021 19:53
Embed
What would you like to do?
<?php
/* NOTES:
* 1. I used $post_ID and not $post_id just because WordPress uses the uppercase
* "ID" and not "id". I also used the second parameter passed to the function,
* i.e. $post.
*
* 2. If your code still doesn't work, post a copy of the code on Pastebin.com or
* GitHub.com.
*/
add_action( 'save_post_cars', 'wpse_387941_set_slug', 10, 2 );
function wpse_387941_set_slug( $post_ID, $post ) {
$meta = array(
get_post_meta( $post_ID, 'maker', true ),
get_post_meta( $post_ID, 'model', true ),
get_post_meta( $post_ID, 'year', true ),
);
$new_slug = implode( '-', array_filter( $meta ) );
if ( strtolower( $new_slug ) === $post->post_name ) {
return;
}
// unhook this function to prevent infinite loop
remove_action( 'save_post_cars', 'wpse_387941_set_slug', 10 );
wp_update_post( array(
'ID' => $post_ID,
'post_name' => $new_slug,
) );
// re-hook this function
add_action( 'save_post_cars', 'wpse_387941_set_slug', 10, 2 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment