post_type_link filter causes 404 on the CPT page it’s used on

When i change the permalink of my CPT using filters it gives a 404. I clicked save in the permalinks settings and switched and saved, but there’s still a 404. Is there some kind of hooking up i need to do with a rewrite to make this work?

function my_permalinks($permalink, $post, $leavename) {
    $post_id = $post->ID;
    if($post->post_type != 'model-list' || empty($permalink) || in_array($post->post_status, array('draft', 'pending', 'auto-draft')))
        return $permalink;
    $parent = $post->post_parent;
    $parent_post = get_post( $parent );
    $permalink = str_replace('model-list/', '', $permalink);
    return $permalink;
}
add_filter('post_type_link', 'my_permalinks', 10, 3);

the url is looking correct, but it gives a 404

1 Answer
1

post_type_link is a filter that is applied to the URL for a post before it’s returned by get_post_permalink.

So it doesn’t change any rewrite rules and the structure of permalinks is still the same.

So yeah – if you use it to change the structure of links, you have also to change the rewrite rules in such way, that the new link is matched and processed correctly.

Leave a Comment