Senior Full Stack Developer
December 2017
M T W T F S S
« Jun    
 123
45678910
11121314151617
18192021222324
25262728293031

Categories


WordPress Custom Post Types And Permalink Rewrite

MubashirMubashir

WordPress Custom Post Types are really powerful feature and using custom post type one can extend WordPress from the native posts or pages to the content of your choice.

One problem which many novice developers come across while creating custom posts type is that they manually have to flush permalink by going into WordPress settings => Permalinks. Manually updating permalinks is a not a good choice and you can not left this job for your end users. So what is the solution?

Flush Rewrite Rules

WordPress has a useful function flush_rewrite_rules() which can be used with custom posts types. Flushing the rewrite rules is an expensive operation, there are tutorials and examples that suggest executing it on the ‘init‘ hook. This is bad practice. It should be executed either on the ‘shutdown’ hook, or on plugin/theme (de)activation.

Let’s suppose you have register custom post type

Above code will add your custom post type, but after you create first custom post and then go to view the post on the fronted it will show you page not found error.

Why is this? because at this stage WordPress don’t have any information about this custom post type permalink structure. One solution could be to manually regenerate permalink by going to settings => permalinks but that’s not the ideal solution. If you want the solution stay with me….

Adding Rewrite Rules on Plugin/Theme activation

and if you have register your custom post type inside your theme functions.php then do this

After you have done this you have automated the task of manually regenerating the permalinks for your newly created custom post type.

Comments 0
There are currently no comments.