[ad_1]
How do I change the URL slug for posts in CPTs to be more simplified?
Right now, let’s say the post is domain .com/CPTname/post-title. I would like it to just be domain .com/post-title, completely cutting out the name of the custom post type. Ideally, if instead of using the post title for the slug if I could use an ACF field from within that post, that would be even better.
Edit: I’m using ACF to make the custom post types.
[ad_2]
I started looking into this exact thing yesterday but wasn’t able to get it working. Revisiting today. This SO post seems to be on the right track
You could definitly use an ACF field for the title, here is a sample code snippet you can start with:
add_filter(‘post_type_link’, ‘xyz_cpt_link’, 10, 2);
function xyz_cpt_link($data, $postarr)
{
$post_type = get_post_type($postarr[‘ID’]);
if (“your_cpt” != $post_type) {
return $data;
}
$custom_slug = isset($_POST[‘acf_field’]) ? $_POST[‘acf_field’] : get_field(‘acf_field’, $postarr[‘ID’]);
$data[‘post_name’] = wp_unique_post_slug(sanitize_title($custom_slug, ‘author’), $postarr[‘ID’], $postarr[‘post_status’], $postarr[‘post_type’], $postarr[‘post_parent’]);
return $data;
}
I’ve used this exact method in the past and it worked fine, I had one issue with rewrite rules, but I fixed it by hooking the following function to `init` action
add_rewrite_rule(
‘your_cpt/([^/]+)?$’,
‘index.php?post_type=your_cpt&name=$matches[1]’,
‘top’
);
You might need to update and extend the code above to work for you. I’ve implemented this using custom fields instead of ACF fields and it worked like charm.