flush_rewrite_rules on save_post Does Not Work on First Post Save

I know this has already been answered, but I felt as if it wasn’t 100% real clear what the actual solution was.

Here’s my answer to add some clarification.

He’s right… You can’t flush rewrite rules on save_post, because that action hook is fired AFTER the init action hook has been fired.

As you know, Post Types and Taxonomies are registered on the init hook.

TLDR; You can’t flush_rewrite_rules(); on save_post action hook.

There’s a workaround…

You need to set an option value to 1 on save_post action hook. Then check that option for value of 1 and flush rewrite rules on init action hook.

Example:

function mbe_late_init_example() {

    if ( ! $option = get_option( 'my-plugin-flush-rewrite-rules' ) ) {
        return false;
    }

    if ( $option == 1 ) {

        flush_rewrite_rules();
        update_option( 'my-plugin-flush-rewrite-rules', 0 );

    }

    return true;

}

add_action( 'init', 'mbe_late_init_example', 999999 );


function mbe_save_post_example( Int $post_id = null, \WP_Post $post_object = null ) {

    if ( ! $post_id || ! $post_object ) {
        return false;
    }

    # Specific Post Type
    if ( $post_object->post_type != 'my-plugin-settings' ) {
        return false;
    }

    # Specific Post Object (OPTIONAL)
    if ( $post_object->post_name != 'general-settings' ) {
        return false;
    }

    update_option( 'my-plugin-flush-rewrite-rules', 1 );

    return true;

}

add_action( 'save_post', 'mbe_save_post_example', 10, 2 );

Leave a Comment