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?

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

1 Answer 1

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 and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.