Hi guys so I have some data hitting my WP from an external company at /wp-json/wp/v2/jobs/ to be imported as a post.
This data contains JSON that needs to be imported, however it tried to set taxonomies using strings e.g. "Manager" rather than the term_id which would be say "381". This means I get an error returned.
{
"code": "rest_invalid_param",
"message": "Invalid parameter(s): job_location, job_industry, job_sector",
"data": {
"status": 400,
"params": {
"job_location": "job_location[0] is not of type integer.",
"job_industry": "job_industry[0] is not of type integer.",
"job_sector": "job_sector[0] is not of type integer."
}
}
}
So what I want is when they post this value to us, for example:
"job_sector":"Manager"
I want to instead loop through our taxonomies, and find the ID for this "Manager" job_sector, rebuild the JSON and THEN have WP import the data I pass, error free with the proper ID.
Can anyone help on how I can intercept the JSON and pass it along in the proper format?
I tried "rest_pre_dispatch" but this seems to be only editing the result sent back to them, it has already been processed by WP.
EDIT: Here is my code:
function wpse281916_rest_check_referer( $result, $server, $request ) {
if ( null !== $result ) {
// Core starts with a null value.
// If it is no longer null, another callback has claimed this request.
// Up to you how to handle - for this example we will just return early.
return $result;
}
$array = json_decode($result, true);
$term = get_term_by('name',$array["job_sector"],'job_sector');
$term = json_decode(json_encode($term),true);
$termid = $term['term_id'];
$array['job_sector'] = $termid;
$result = json_encode($array);
return $result;
}
// add the filter
add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 );
EDIT2: After suggestion
function wpse281916_rest_check_referer( $result, $server, $request ) {
if ( null !== $result ) {
// Core starts with a null value.
// If it is no longer null, another callback has claimed this request.
// Up to you how to handle - for this example we will just return early.
return $result;
}
$array = json_decode($request, true);
$term = get_term_by('name',$array["job_sector"],'job_sector');
$term = json_decode(json_encode($term),true);
$termid = $term['term_id'];
$array['job_sector'] = $termid;
$request = json_encode($array);
return null;
}
// add the filter
add_filter( 'rest_pre_dispatch', 'wpse281916_rest_check_referer', 10, 3 );
job_sector
endpoints