Not really an How To but just a quick post to help you guys who are stuck looking for a fix on the 404 problem caused by permalink structure other then the default for custom post type.
Bits of background
So i wrote a short plugin for a client of mine with a custom post type (CPT in short) called deals using what is quickly becoming my favorite WordPress function Register_post_type which accepts a great list of arguments, but in this case I'm talking about the rewrite argument that can accept:
- False - to prevent rewrite
- Array -
- 'slug' - prepend posts with this slug - defaults to post type's name
- 'with_front' - allowing permalinks to be prepended with front base (example: if your permalink structure is /blog/, then your links will be: false->/news/, true->/blog/news/) - defaults to true
- 'feeds' - default to has_archive value
- 'pages' - defaults to true
So as usual i used a simple :
'rewrite' => array('slug' => 'deal')
and my post type was registered all nice and good and i could see it correct when using the default permalink stracture (?p=32) but when I changed the permalink structure to somthing other then the default i started getting a 404 - page not found and after hours of digging around i found that i need to flush the rewrite rules right after registering the post type.
The Magic Fix
So after finding that out the fix was easy, all i did was add :
flush_rewrite_rules( false );
to my register post type function.
Ok So it appears that `flush_rewrite_rules` is a very resource expansive function and therefor running it on every page load is a bad idea so here is a better solution, In your register post type function add the following:
$set = get_option('post_type_rules_flased_POST-TYPE-NAME-HERE'); if ($set !== true){ flush_rewrite_rules(false); update_option('post_type_rules_flased_POST-TYPE-NAME-HERE',true); }
Hope this helps you guys and saves you some time.