carbon-fields
carbon-fields copied to clipboard
Edit association option requests are unauthenticated and do not return edit links
Version
- Carbon Fields: 3.3.2
- WordPress: 5.9.2
- PHP: 7.4
Expected Behavior
When editing an association field, all options have an edit link.
Actual Behavior
When editing an association field, only options loaded initially (server rendered) have edit links. Options fetched via API requests (searched or paginated) do not have edit links.
Container definition
Container::make('post_meta', __('Associations'))
->add_fields([
Field::make('association', 'associated', 'Associated')
]);
Steps to Reproduce the Problem
- Edit a post
- Search in the "Associated" field
- See that no edit link is retrieved
Comments
This looks to be due to no nonce being provided in the API requests, resulting in those requested being considered unauthenticated by the API. The get_edit_post_link method and similar get_edit_xxx_link methods that Carbon Fields uses to get the edit links require user authentication and return null because there is no current user in the API handler context.
Setting the current user manually via wp_set_current_user(1) (assuming user 1 is an admin) in the API handler results in edit links appearing as expected, but is not acceptable for production use.
A possible workaround:
add_filter(
'rest_pre_dispatch',
function ($result, WP_REST_Server $server, WP_REST_Request $request) {
if ($request->get_route() === '/carbon-fields/v1/association/options') {
wp_set_current_user(1); // use the ID of any user with permissions to edit posts
}
return $result;
},
10,
3,
);
This will set the current user for the association option request handler to the specified user, making edit links accessible assuming the provided user has edit permissions. The set user will be limited to the association option requests and will only be within the scope of that request handler, so it may be acceptable for some cases.