Description
Bug Report
- Yes, I reviewed the contribution guidelines.
- Yes, more specifically, I reviewed the guidelines on how to write clear bug reports.
Describe the current, buggy behavior
Describe how other contributors can replicate this bug
Describe what you expect as the correct outcome
in theme functions.php add:
function init_cb() {
var_dump( 'this is init' );
}
add_action( 'init', 'init_cb' );
function admin_init_cb() {
var_dump( 'this is admin init' );
}
add_action( 'admin_init', 'admin_init_cb' );
Then run:
wp --user=1 --context=admin eval ""
You will get:
this is admin init
this is init
However, this is the opposite order of what it would normally be in an wp-admin request.
Let us know what environment you are running this on
WP 6.6
WP CLI 2.11.0
Provide a possible solution
-
The issue is https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L45 is run on init hook with earliest priority (PHP_INT_MIN)
To keep it consistent with WP core, it needs to be loaded onwp_loaded
withPHP_INT_MAX
(last hook in settings.php) -
And the user auth https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L44 is wrong too. Normally the user is set up already on
plugins_loaded
- therefore that needs to be called onplugins_loaded
withPHP_INT_MIN
-
Also there's a bug here https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L63 - when a --user is provided, it should use that user and not arbitrarily fall back to ID 1 since this will make
current_user_can
checks fail and therefore the context=admin is pointless, since it's an unauthenticated request anyway
EDIT: looks like the correct code is there https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Runner.php#L1655 but the user then gets overwritten by the wrong user in https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L63 (since that init hook was added later it runs after) - I guess a simple check whether the user is set already in https://github.com/wp-cli/wp-cli/blob/main/php/WP_CLI/Context/Admin.php#L63 would be sufficient before overwriting it with id 1