• Resolved Himanshu Ahuja

    (@himanshuahujaofficial)


    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 flush

    add_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();
        }
    }
Viewing 1 replies (of 1 total)
  • Plugin Author Rafin

    (@rafinkhan)

    Hi @himanshuahujaofficial,

    Wow! Thank you for your great suggestion. I have already forwarded this to our Development team and this sounds very promising. We will definitely work on this and implement in the future.

    Thank you, have a nice day!

Viewing 1 replies (of 1 total)
  • The topic ‘Wrong Use of flush_rewrite_rules in CPT register function’ is closed to new replies.