Make WordPress Core

Opened 3 years ago

Last modified 2 years ago

#51805 new defect (bug)

Clarify the prerequisites for updating the .htaccess file in flush_rewrite_rules()

Reported by: sergeybiryukov's profile SergeyBiryukov Owned by:
Milestone: Future Release Priority: normal
Severity: normal Version:
Component: Rewrite Rules Keywords:
Focuses: docs Cc:

Description

Background: #51723

In flush_rewrite_rules(), the documentation for the $hard parameter currently says:

Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard).

However, this does not mention that WP_Rewrite::flush_rules() only calls save_mod_rewrite_rules() if the function exists, which is only loaded in the admin.

Moreover, there is a section in wp-admin/admin.php to flush the rewrite rules when a database version is bumped, but save_mod_rewrite_rules() is not loaded yet at that point, leading to some confusion.

The function should clearly state what exactly is needed for updating the .htaccess file.

Another idea suggested in #51723 is to make sure save_mod_rewrite_rules() is loaded to regenerate the file when flushing the rewrite rules after database version bumps, see comment:5:ticket:51723.

Change History (3)

This ticket was mentioned in Slack in #core by metalandcoffee. View the logs.


3 years ago

#2 @lukecarbis
3 years ago

  • Milestone changed from 5.7 to Future Release

#3 @bwmarkle
2 years ago

+1

Usually it's Stack Overflow that answers all my questions, but today it was this trac ticket!

I'm creating a REST call to allow changing of a siteurl, and flush_rewrite_rules() wasn't working as expected. I ended up writing a wrapper function.

<?php
/**
 * A wrapper for WordPress' flush_rewrite_rules.
 *
 * Wrapper function is necessary because rewriting the .htaccess only works if the
 * save_mod_rewrite_rules() function exists, which only does in admin. This method ensures it's
 * there.
 *
 * @link https://core.trac.wordpress.org/ticket/51805
 *
 * @param bool $hard Whether to update .htaccess (hard flush) or just update rewrite_rules option
 *                   (soft flush).
 */
public static function flush_rewrite_rules( $hard = true ) {
        // A requirement for rewriting the .htaccess file.
        if ( $hard && ! function_exists( 'save_mod_rewrite_rules' ) ) {
                require_once ABSPATH . 'wp-admin/includes/misc.php';
        }

        flush_rewrite_rules( $hard );
}
Note: See TracTickets for help on using tickets.