0

I am trying to update a metadata I created from the front-end with a click event.

{
  "id": 1248,
   .
   .
   .
   "metadata": {
       "wishlist_array": [
          ""
        ],
   .
   .
   .

The idea is to add a post ID to the array, the post ID is from another post type. And it is passed on with updateWishlist() function triggered by a click event

Here is my JS:

updateWishlist: function(e, postID) {
      e.stopImmediatePropagation();

      // GET
      fetch("http://ohalocal.local/wp-json/wp/v2/oha_wishlist/1248")
        .then(function(response) {
          return response.json();
        })
        .then(function(wishlistPost) {
          var wishlist_array = wishlistPost.metadata.wishlist_array; //Getting the current metadata array
          wishlist_array.push(postID); //Add postID to array

          // POST
          fetch("http://ohalocal.local/wp-json/wp/v2/oha_wishlist/1248", {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "X-WP-Nonce": phpVarObj.nonce
            },
            body: JSON.stringify({
              metadata: { wishlist_array: JSON.stringify(wishlist_array) }
              //Send new array to server
            })
          })
            .then(function(response) {
              console.log(response);
              return response.json();
            })

The method I created is working but it adds array inside array, with multiple levels. As follow:

["["["["["["","1234"]","1233"]","1234"]","1234"]","1234"]"]

How can I have it as a single level array?

  • Try using metadata: { 'wishlist_array': wishlist_array }. – Sally CJ Jun 19 at 9:30
  • 1
    Thanks Sally, besides that, I realized that wishlistPost.metadata.wishlist_array is not an array :) – stemon Jun 20 at 14:22
  • Don't forget to accept your answer. :) – Sally CJ Jun 20 at 15:06
  • Oopps, Thanks:) – stemon Jun 21 at 19:59
0

Two things need to be changed

1 - wishlistPost.metadata.wishlist_array which is the metadata returns an object with a string inside, not an array.

var wishlist_array = wishlistPost.metadata.wishlist_array[0]; //Get current string

          wishlist_array += postID + ","; //Concat new ID to the current string

2 - JSON.stringify(wishlist_array) is not needed as stated above wishlist_array is a string already. As Sally CJ commented the body should be as follow:

body: JSON.stringify({
              metadata: { wishlist_array: wishlist_array }
            })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.