I wanted to change the slug of a certain post type (in this case, article) into whatever a certain value in its custom field.
I went to functions.php and put this code.
function na_remove_slug( $post_link, $post, $leavename ) {
if ( 'article' != $post->post_type || 'publish' != $post->post_status ) {
return $post_link;
}
# get the custom field value here to be the slug
$post_name = get_field('filter_category', $post->ID)->post_name;
# replace the "article" by the value of the custom field
$post_link = str_replace( '/' . $post->post_type . '/', "/$post_name/", $post_link );
return $post_link;
}
add_filter( 'post_type_link', 'na_remove_slug', 10, 3 );
When I query the custom post types, it appears as if its slug was altered, for example: www.example.com/article/some-title into www.example.com/design/some-title
Where design is my custom field value.
But when I finally visit www.example.com/design/some-title, I get a 404. But if I visit www.example.com/article/some-title, it returns the correct web page.
I understand that my code only changes how the link appears when it is displayed, but how can I show my single post correctly using the slug that I have altered?
If you need more clarification, please don't hesitate to comment.