Wrong Use of flush_rewrite_rules in CPT register function
-
Hi There,
we found that in
"includes/class-betterdocs-docs-post-type.php"
file plugin is registering CPT and calling flush_rewrite_rules in there. And you can see this function “register_post” is attached to init hook. Which means that flush_rewrite_rules is called on each page call hence causing too much load on database.And we found that after commenting this function there was 50% reduction in database and web server loads.
Better way:
you can call this when plugin is activated or you can find some good examples done by other developers too.Like this:
function myplugin_activate() { // register taxonomies/post types here flush_rewrite_rules(); } register_activation_hook( __FILE__, 'myplugin_activate' ); function myplugin_deactivate() { flush_rewrite_rules(); } register_deactivation_hook( __FILE__, 'myplugin_deactivate' );
And when plugin settings is updated by ADMIN in backend.
or
third approach suggested by Jack Johansson
https://wordpress.stackexchange.com/questions/315001/flush-rewrite-rules-on-init-or-rest-api-init
here is sample code, which if your rewrite rules are present then don’t flushadd_action( 'init', 'wpse315001_flush_rewrite_rules', 99999 ); function wpse315001_flush_rewrite_rules(){ // Get the rewrite rules $rules = get_option('rewrite_rules'); // Check if your semi-unique rule exists in this string if ( ! strpos( $rules, 'your-rewrite-rules' ) ) { // Flush'em All! flush_rewrite_rules(); } }
- The topic ‘Wrong Use of flush_rewrite_rules in CPT register function’ is closed to new replies.