I have a simple plugin that I’m working on, and in the init action I’m using add_rewrite_rules, but I get a fatal error “Call to a member function add_rule() on null in wp-includes/rewrite.php:143”.
My code:
add_action( 'init', [ __CLASS__, 'addRules' ]);
public static function addRules()
{
add_rewrite_rule(
'^my-acct(/.*)/?$',
'index.php?pagename=my-acct',
'top'
);
}
If I add the following at the top of the method, the error goes away:
if( ! is_object( $GLOBALS['wp_rewrite'] ) )
$GLOBALS['wp_rewrite'] = new WP_Rewrite();
I’m just wondering why I don’t see other plugins do this? What am I doing wrong?
1
Yes, the problem was that in another part of the plugin I was calling the static method addRules, and it happening outside of any hook. Once I fixed that, all is well.