Let’s write our own custom api route to update ACF fields. The api request will have two handlers – POST and GET. GET – will display any information upon user request by post id – method my_awesome_func(). POST – will update a specific post by post id – method my_awesome_func_two().
$request is a method parameter that receives data from POST and GET requests via api.
Line update_field(‘field_65c5cbb2d73ea’, $response[‘files’], $response[‘id’]);
means that the ACF field with id field_65c5cbb2d73ea will be updated for the post with id $response[‘id’]. $response[‘files’] is the value of the ACF field (what will be written there).
// Your rest api ACF route
add_action( 'rest_api_init', function(){
register_rest_route( 'update_acf/v2', '/post/', array(
array(
'methods' => 'GET',
'callback' => 'my_awesome_func',
),
array(
'methods' => 'POST',
'callback' => 'my_awesome_func_two',
'args' => array(
'id' => array(
'type' => 'string', // the parameter value must be a string
'required' => true, // parameter required
),
'files' => array(
'type' => 'string', // the parameter value must be a string
'required' => true, // parameter required
),
),
'permission_callback' => function( $request ){
// only an authorized user has access to the endpoint
return is_user_logged_in();
},
// or in this case it can be written more simply
'permission_callback' => 'is_user_logged_in',
)
) );
} );
function my_awesome_func( WP_REST_Request $request ){
return 'test';
}
function my_awesome_func_two( WP_REST_Request $request ){
$response = array(
'id' => $request->get_param('id'),
'files' => $request->get_param('files')
);
update_field('field_65c5cbb2d73ea', $response['files'], $response['id']);
return $response;
}
You can check the operation of this api route using the Postman program:
/wp-json/update_acf/v2/post/ – api route string
1629 – post id
string_value – значение поля ACF