Unlock your potential with a Pro Membership
Here is where you propel your career forward. Come join us today. Learn more.
Flush Rewrite Rules
Lab: Custom Post Type Basics
Video Runtime: 13:44
In this episode, you will learn about why, when, what, and how of flushing the rewrite rules for your new custom post type. You’ll learn about permalinks, Rewrite API, and how the page request is mapped through the rewrite rules to figure out what record to pull from the Posts database table.
The starter plugin you got at the start of this lab has the rewrite the right way. It’s attached to the plugin activation event. That is the right way to do it.
Why? Rebuilding (flushing) rewrites is an expensive process. It takes a lot of time to do it, which slows down the website.
Flushing rewrite rules after registering a custom post type slows down your website #WordPress Share on XFar too often I see people adding flush_rewrite_rules
right after the register_post_type(). That is wrong. You will see why in this episode. Why? It happens on every single web page request. It slows down your website. That’s bad. Listen to me. Don’t do it.
Instead, attach the rewrite to the plugin activation.
Let’s explore permalinks, rewrites, activation, and the database.
Update: Improvement for the Deactivation Hook
In the video, you saw that if you make the deactivate callback register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
it didn’t give us a 404 as it should. Right? To fix that wonky behavior, let’s add a callback and then just delete out the “rewrite rules” option in the database.
The revised code then is this:
[php]
/**
* The plugin is deactivating. Delete out the rewrite rules option.
*
* @since 1.0.1
*
* @return void
*/
function deactivate_plugin() {
delete_option( ‘rewrite_rules’ );
}
[/php]
Now on plugin deactivation, you do get a 404 instead of the weird Posts Page coming up.
Code. Eat. Code. Sleep. Dream about Code. Code.
Episodes
Total Lab Runtime: 01:20:49
- 1 Lab Introductionfree 02:33
- 2 What is a Custom Post Type?free 03:12
- 3 Plugin Overviewpro 12:09
- 4 Minimum Configurationpro 07:18
- 5 Configure Labelspro 12:52
- 6 Configure Post Type Featurespro 07:21
- 7 Exclude Post Type Featurespro 08:25
- 8 Flush Rewrite Rulespro 13:44
- 9 Configuring Argumentspro 10:48
- 10 Wrap it Uppro 02:27