I'd like use a specific custom field in a custom post type as the slug for the post.
My custom post type is members
and the custom field that I want to use as the slug is member_user
. How can I do this?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.
Sign up to join this communityYou could do this like saving post meta. You would unhook out of the current hook and update the post, if you don't do that you will end up in an infinite loop:
/**
* Save Custom Data
* @param int $post_id
* @param Post Object $post
*/
function save_custom_meta_boxes( $post_id, $post ) {
// If we're not in the right place, bailout
if( ! isset( $post ) || wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
return $post_id;
}
// `members` Type Metaboxes
if( 'members' == $post->post_type ) {
// Update Post Slug
if( isset( $_POST['member_user'] ) && ! empty( $_POST['member_user'] ) ) {
remove_action( 'save_post', 'save_custom_meta_boxes' );
wp_update_post( array( 'ID' => $post_id, 'post_name' => sanitize_title( $_POST['member_user'] ) ) );
add_action( 'save_post', 'save_custom_meta_boxes' );
}
}
}
add_action( 'save_post', 'save_custom_meta_boxes', 10, 2 );
IF the user has set a value into the member_user
field we will remove the current action, update the post to the new slug using the same field, and rehook the action to continue processing any other post meta values. We take advantage of sanitize_title()
to ensure the user doesn't add anything malicious.
member_user
and not something different. Ensure that members
is actually the post type name. Additionally you may need to print_r($_POST); die();
to get to the bottom of the issue. I just tested the above on a custom install and it worked as expected.
member_user
to associate amember
with aUser
. The full name of theUser
ought to be the title, but I haven't set it, figuring I can just do it on the front end. So now the Titles, and in turn the slugs get set toauto-draft
automatically. But ideally I'd like to have the User's name be the Title and the slug.