Senior Full Stack Developer
April 2024
M T W T F S S
1234567
891011121314
15161718192021
22232425262728
2930  

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

function my_custom_post_type(){
 /***Code for your custom post type goes over here **/
}
add_action('init', 'my_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

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
register_activation_hook( __FILE__, 'myplugin_flush_rewrites' );
function myplugin_flush_rewrites() {
// call your custom post type registration function here (it should also be hooked into 'init')
	my_custom_post_type();
//Flush rewrite rules so that users can access custom post types on the front-end right away
	flush_rewrite_rules();
}

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

/* Flush rewrite rules for custom post types. */
add_action( 'after_switch_theme', 'flush_rewrite_rules' );

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.