Skip to content

Instantly share code, notes, and snippets.

@rmpel
Last active June 3, 2024 14:26
Show Gist options
  • Save rmpel/d7313eaa9cf72660106bedad2115047c to your computer and use it in GitHub Desktop.
Save rmpel/d7313eaa9cf72660106bedad2115047c to your computer and use it in GitHub Desktop.
Fix WordPress Author dropdown in multi-role set-up
<?php
/**
* If your website has custom roles and capabilities, and post-types with custom edit_posts capabilities,
* the dropdown on the _overview_ page, _quick edit_ is CORRECT.
* however, the dropdown on the _create new post_ or _edit existing post_ pages is NOT.
* This code fixes that.
*
* @package FixesByRemonPel
* @subpackage FixesByRemonPel/RestUserQuery
*/
add_filter(
'rest_user_query',
function ( $prepared_args ) {
// If asking for deprecated `who` parameter, and referer is set, try to determine the post type and set the capability.
if ( ! empty( $prepared_args['who'] ) && ! empty( $_SERVER['HTTP_REFERER'] ) ) {
$referer_url = parse_url( $_SERVER['HTTP_REFERER'] );
parse_str( $referer_url['query'], $referer_query );
// We successfully parsed the query string.
if ( $referer_query ) {
// We either have a post or a post_type.
$post_id = $referer_query['post'] ?? 0;
$post_type = $referer_query['post_type'] ?? '';
if ( $post_id || $post_type ) {
// If we have a post_id, we can determine the post_type.
$post_type = $post_type ?: get_post_type( $post_id );
// If we have a post_type, we can determine the capability.
if ( $post_type ) {
$post_type_object = get_post_type_object( $post_type );
$capability = $post_type_object->cap->edit_posts;
// If we have a capability, we can replace the `who` argument with the `capability` argument.
if ( $capability ) {
$prepared_args['capability'] = $capability;
unset( $prepared_args['who'] );
}
}
}
}
}
return $prepared_args;
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment