Using the rest_pre_dispatch
hook is probably the most straightforward way to go, but you need to be careful about putting your new request data back into the WP_REST_Request
object properly.
You were reassigning the WP_REST_Request
object to an array of request data. Those changes are not persisted because the parameter is not passed by reference. Instead, you want to modify the WP_REST_Request
object.
You can assign a parameter to the request object using array like syntax, or by using WP_REST_Request::set_param( $param_name, $param_value )
.
You should also check to make sure you are only running this code on the correct route. I’d also move the priority to fire the hook earlier since you essentially are saying that this change should apply to everything happening on this request.
function wpse281916_rest_check_referer( $result, $server, $request ) {
if ( '/wp/v2/jobs' !== $request->get_route() || 'POST' !== $request->get_method()) {
return $result;
}
$job_sector = $request['job_sector'];
if ( null === $job_sector ) {
return $result;
}
$term = get_term_by( 'name', $job_sector, 'job_sector' );
if ( $term && ! is_wp_error( $term ) ) {
$request['job_sector'] = $term->term_id;
} else {
$request['job_sector'] = 0;
}
return $result;
}
// add the filter
add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 0, 3 );