I'm wanting to change a WordPress post's permalink (post_name
) dynamically every time time a post is saved/updated by pulling from a custom field present in the post and replacing the permalink with this value. I have code within functions.php
which is working, except that it appends -2
to the permalink. I assume this is because something is occurring twice, the first time resulting in the permalink I want, and the second resulting in WordPress responding to the "duplicate" by adding -2
.
This is the current code:
add_action('save_post', 'change_default_slug');
function change_default_slug($post_id) {
if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
return;
if ( !current_user_can('edit_post', $post_id) )
return;
remove_action('save_post', 'change_default_slug');
wp_update_post(array('ID' => $post_id, 'post_name' =>get_post_meta($post_id,'request_number',true)));;
add_action('save_post', 'change_default_slug');
}