I have a simple CPT
called App
in the backend.
I have added a custom usermeta
field called favorite_apps
to Users
On the front end, I show a list of apps, and then the user presses a star(☆) icon to add it to their list of favorites ( stored as an array of post_id
in the favorite_apps
custom user meta field ).
I decided to do this using the REST API and built a custom endpoint:
/wp-json/my-site/v1/users/{user_id}/favoriteapps
Example: /wp-json/my-site/v1/users/555/favoriteapps
This route accepts POST,PUT,PATCH
using WP::Editable
and GET
using WP::Readable
.
A GET
request returns a list of user 555
's current favorite_apps
A POST
request, and pass app=123
in the body I add the App ID 123
to app_favorites
For removing an app from the list, I'm not sure. I'm not DELETING the list of favorite_apps, I'm removing one of the items.
It feels natural to use POST
and DELETE
to add/remove from the list, but:
- Is there a convention that I can follow when modifying a list of items?
- Should I be using
PUT
orPATCH
and passing anaction
as another parameter? - Do I have to be concerned about browser support for certain methods?
For reference, this is how I add app 123
to/from user 555
in js/jQuery:
var uid = 555;
var appId = 123;
$.ajax({
method : 'POST',
data : { app : 123 },
url : '/wp-json/my-site/v1/users/' + uid + '/favoriteapps',
success: function( data ){
// code to tell user of success or failure;
}
});
PUT
but rely onPOST
andDELETE
to different endpoints. Once I wrote it down, it make complete sense.