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.

1 Answer 1


You can try this plugin, I think this will work for you. You can directly change the URL on your page by clicking on URL to whatever you want.

Hope this would be helpfull.

  • Hi Baikare! I already have that plugin. But unfortunately, I need to do the URL rewriting programmatically, as I have existing posts already. It will be too much if I rewrite all of them individually. Thank you though!
    – Bwrites
    Jul 23, 2018 at 13:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.