How To Refresh Permalinks Automatically Without A Plugin

Looking to auto-refresh WordPress permalinks automatically, without a plugin? This guide will show you ow you can do this pragmatically.

Auto-refresh permalinks automatically pragmatically

In your theme’s functions.php file, you need to add the following code at the end of it, in order to refresh permalinks pragmatically.

function wpza__flush_perma_on_404() {
     if ( is_404() ) {
          global $wp;
          $check = get_transient( 'permalinks_flushed_recently' );
          if ( $check === false ) {
               flush_rewrite_rules();
               set_transient( 'permalinks_flushed_recently', 'yes', 5 * MINUTE_IN_SECONDS );

               wp_redirect(home_url( $wp->request ));
               exit;
          }
     }
}
add_action( 'template_redirect', 'wpza__flush_perma_on_404' );

What happens if the site uses page-caching, and that needs refreshing too?

If your site uses front-end page-caching, you may see that even after refreshing, your pages are still 404ing. This is due to page-caching, which also needs to be cleared.

Below is an example using the Litespeed Cache plugin, on how to pragmatically refresh your website’s cache — whilst refreshing permalinks. Note that you will need to adjust this, based on your page-caching plugin of choice.

function wpza__flush_perma_on_404() {
     if ( is_404() ) {
          global $wp;
          $check = get_transient( 'permalinks_flushed_recently' );
          if ( $check === false ) {
               flush_rewrite_rules();
               set_transient( 'permalinks_flushed_recently', 'yes', 5 * MINUTE_IN_SECONDS );

               if ( class_exists( '\LiteSpeed\Purge' ) ) {
                    do_action( 'litespeed_purge_all' );
               }

               wp_redirect(home_url( $wp->request ));
               exit;
          }
     }
}
add_action( 'template_redirect', 'wpza__flush_perma_on_404' );