Make WordPress Core

Opened 8 years ago

Last modified 5 years ago

#36579 new enhancement

global $wp_rewrite not set when create_initial_post_types() first run

Reported by: bobbingwide's profile bobbingwide Owned by:
Milestone: Priority: normal
Severity: normal Version: 4.4
Component: Posts, Post Types Keywords:
Focuses: Cc:

Description

The global $wp_rewrite is set in wp-settings.php, after create_initial_post_types().

If you want to hook into the 'register_post_type_args' filter, to set $args->rewrite then you currently have to jump through hoops to avoid an
Uncaught error Call to a member function add_rewrite_tag() on null

Could the call to set $GLOBALS['wp_rewrite'] be moved to before create_initial_post_types()?
Or perhaps some defensive programming in rewrite.php to test if $wp_rewrite is set.
Functions add_rewrite_tag and add_permastruct are candidates for that change.

Change History (3)

#1 @dd32
8 years ago

It's worth noting, that plugins are loaded after the initial call of create_initial_post_types(). It's only mu-plugins and other dropins which get in there first that this could affect.

I actually think the solution in this case is that plugins shouldn't hook into register_post_type_args until at least plugins_loaded is fired.

create_initial_post_types() is called twice as many plugins expected the post types (and taxonomies) to be setup before init.

#2 @bobbingwide
8 years ago

In my case I discovered the problem because the plugin was network activated; and network activated plugins are loaded after MU plugins.

I could wait for 'plugins_loaded' but it's probably safer to wait for 'setup_theme', since $wp_rewrite should have been initialised by then.
'after_setup_theme' is too late if it's the theme that's registering the post type I want to override.

As an aside: What's the reason for the @ preceding the comment
// @plugin authors: warning: these get registered again on the init hook.

So, follow on question. Should there be a comment in the docblock for 'register_post_type_args' saying when it's safe to hook into this filter? Or will this TRAC suffice?

#3 @dd32
8 years ago

I could wait for 'plugins_loaded' but it's probably safer to wait for 'setup_theme', since $wp_rewrite should have been initialised by then.

  • You should run add_action()/add_filter() on plugins_loaded or later
  • Adding the action on plugins_loaded is fine, as the register_post_type_args filter won't fire again until either a) A plugin registers a post type, or b) init when create_initial_post_types() is run again.
  • You shouldn't run code which expects WordPress to be initialised (such as $wp_rewrite) until init or later
Note: See TracTickets for help on using tickets.