The WordPress core function flush_rewrite_rules doesn’t work during ajax requests, can we still programmatically flush the rewrite rules in this case?
Yes, we can, and the solution is very simple.
As you know when you visit the permalinks page, the rewrite rules are flushed.
So why don’t we just programmatically visit the permalinks page sending the authorization cookies?
Here you have the code:
//Remotely visit permalinks page to flush rewrite rules for ajax requests function eos_fp_refresh_rewrite_rules_during_ajax(){ $cookies = array(); foreach ( $_COOKIE as $nome => $value ) { $cookies[sanitize_key( $nome )] = sanitize_text_field( $value ); } $args = array( 'cookies' => $cookies ); wp_remote_get( admin_url( 'options-permalink.php' ),$args ); }
This function will flush the rewrite rules if you call it inside your ajax PHP function that runs when an authorized user is logged-in.
It’s useful if you want to flush the rewrite rules when an administrator saves some options via ajax.
If you are not using ajax, better to use the core function flush_rewrite_rules.