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


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.

  • ok thank you, but what should i put in add_rewrite_rule ? – Tintinabulator Zea Apr 21 '19 at 8:25
  • i am removing the CPT name from the url, so i don't think I can find it on index.php because the permalink doesn't contain post_type info – Tintinabulator Zea Apr 21 '19 at 8:32
  • i used this guide to try and do it 1fix.io/blog/2016/02/05/parent-from-another-cpt i set the CPT to have a page that's a parent, it actually works if i don't set the parent – Tintinabulator Zea Apr 21 '19 at 8:35
  • @TintinabulatorZea if you’re removing CPT name, then it won’t be so easy to match these posts using only rewrite rules - these patterns will cause conflicts (there is no way to tell if WP should look for your CPT or a normal page). In such case you have to write some custom code that will check what type of post to search for and get that post. There’s a good answer on how to remove CPT slug from URL somewhere in here (I’m on mobile currently, so it’s not so easy for me to find it, sorry) – Krzysiek Dróżdż Apr 21 '19 at 8:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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