Like others, I want to set a custom post's title from a field. I can do that thanks to previous submissions here. However, I want to generate the slug from the title and urlencode that, in case anyone makes a mistake typing. I run the title through rawurlencode and assign the result to the slug, but what I get is that the slug is NOT encoded, BUT the link to the post IS encoded, so the post is not found by following the link. How can I make the slug match the encoded link? Here is the code I have at the moment. The post type is "resource", field group is "resources-fg", and the field for the title is "resource_title". Thanks.
add_action( 'rwmb_resources-fg_after_save_post', 'swb_update_post_title' );
function swb_update_post_title( $post_id ) {
$my_title = rwmb_meta( 'resource_title', '', $post_id);
if ( post_exists( $my_title, '', 'resource', '' ) ) {
$my_title = substr(md5(rand()), 0, 9);
}
$my_slug = rawurlencode( $my_title );
$my_post = array(
'ID' => $post_id,
'post_title' => $my_title,
'post_name' => $my_slug
);
wp_update_post( $my_post );
}