Support Forum
Support › MB Frontend Submission › Set post title from field AND encode the slugResolved
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 );
}
You can close this. I figured it out. I'm traveling so I'm testing on a Chromebook, and it doesn't allow me to set the permalinks reasonably. Thanks for listening.
Hi Scott! How did you fix this issue?
I was still learning MB. It was simple. In the field group, you can have a field for post.title directly.
Interesting, so did you add a text field and then set it to {post.title} or something? I'm not using a Meta Box group so I'm not exactly sure of how you solved the issue. Appreciate your help 🙂
Ok yeah that makes sense, but did you use the same code as you posted in this thread initially?
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 );
}
No. I would have done something like that but the reason for it evaporated. I don't think that code worked anyway.
I see, but you did fix the issue? Apart from the post_title what else did you do?