Using update_user_meta with an array
-
I’m building a plugin where I’m trying to use a user meta field to store a history of user activity. I’m having a hard time wrapping my head around how to update and store the array of data.
So, my question is: can somebody tell how to update my code? Or, would it be simpler to create a table with this data? Create a new post type?
(I thought a user meta field would be better, so that I wouldn’t clutter the database with another table, but maybe my reasoning is off.)Anyway, here’s what I’m trying to accomplish:
1 – In the front end, the user chooses from a drop-down menu their selection for the day. For example: “Today, I ate an APPLE or ORANGE or BANANA”.
2 – The plugin saves the vote of fruit for the day in the user meta field I callmyplugin-hist
.
3 – The next day, if the user chooses a new fruit, the plugin adds this new fruit to themyplugin-hist
so that we can see what the choice was yesterday and again today.
4 – I’ve tried various ways of storing the data, and I get arrays within arrays, not resembling the structure I have in mind, which should ideally have this structure:array( day 1 => apple day 2 => banana day 3 => apple )
Here’s a sample of my code. So far, I’ve written just the code to save to the database (which is where I need help.)
// This function receives the (int)$fruit vote from another function // (apple is 1, banana is 2, etc) public function i_vote_for($fruit) { global $MainPluginClass; // First, we obtain the user's vote history $hist = get_user_meta($this->ID, 'myplugin-hist', false); // I added this, in case it's a brand-new user with no history if (!array($hist)) $hist = array(); // This is a custom function that returns an int, to count day 1, day 2, etc $d = $MainPluginClass->current_date(); //This is the part where I'm scrathcing my head. //I've tried $hist[$d][] = $fruit; //I've tried $hist[] = array ($d, fruit); $hist[0][] = $fruit; update_user_meta($this->ID, 'myplugin-hist', $hist); // the $this->ID is a shorthand in my plugin for get_current_user... }
- The topic ‘Using update_user_meta with an array’ is closed to new replies.