There seems to be quite a controversial opinion on the WordPress flush_rewrite_rules()
function.
According to the Codex, it is highly discouraged to use this function on the init
action hook.
However:
In a plugin I am working on, I am using add_feed()
to, well, add a feed. The Codex says that this should be run on init
and requires a one-time use of flush_rewrite_rules()
.
See my dilemma ? I need add_feed()
on init
, which requires flush_rewrite_rules()
.
Hence, flush_rewrite_rules()
on init
, which is breaking all custom post type rewrite rules and permalinks, resulting in 404 pages.
So my question is: how should this be done ?
This is what I currently have on init
, that is related to the issue:
add_action( 'init', 'my_foobar' );
function my_foobar() {
// getting some settings
add_feed( $url, $callback );
flush_rewrite_rules();
}
Any help would be greatly appreciated. thanks 🙂
You have to check the existing rewrite rules before you run a flush. If your feed name is
test
, they are stored under the keys'feed/(feed|rdf|rss|rss2|atom|test)/?$'
and'(feed|rdf|rss|rss2|atom|test)/?$'
.So this should do the trick: