Programming – WordPress dev array user meta

Update I did in fact finish a simple version of this with use of a shortcode for admin to view the list. It will make an inline list comma separated of the last 20 unique hostname/ip address for any logged in user, the data can also be clicked on to view on an external site with host info. Some exclusions were added so the ip list can only be shown to the site admin and other features, plus min/max settings for each user. I haven’t work on this in awhile but an unfinished admin menu item was also created with a text input and selection box to do some CRUD functions, currently the script file has to be edited to change settings which is user unfriendly. The project has already come in VERY useful to me and hopefully more will done with it.

Playing around on local server, working on new user meta functions. This one is an ip history array, idea is something like xenforo uses to show a list of all ip’s of any user. I am using the built in WP user_meta functions and storing in user meta, something I typically never use. With this function you can show the admin or user the list, use for admin only functions, set a limit on ips stored and it removes the oldest entry aka array_shift(). For my test code it’s using raw ip’s that are not anonymized but production would be.

Nothing super complicated but I am new with using update and get user_meta, in vanilla PHP so use to writing my own CRUD functions. Some small things made a big difference. I like the easy peasy stuff.

/* 
Setting the last parameter to true makes WP store 
your array as single array for your use in database for my_meta_name 
a:2:{i:0;s:5:"DATA1";i:1;s:5:"DATA2";} otherwise it will create arrays 
inside arrays which could be useful for other functions. 
For my function it only stores an ip string so a single array is ok, 
but later I may change it to do ip => date etc.
*/

/*
 a:2 array items
 i:0 index of item
 s:5 size of item, 5 bytes or characters in this case
 :"data"
*/

// To get data already in the WordPress database if it exists
$data = get_user_meta(get_current_user_id(), 'my_meta_name', true);

// For adding data update_user_meta() 
// Update was superior to add_user_meta() because it will add it if doesn't exist or update if it does, this works best for my use case.

update_user_meta(get_current_user_id(), 'my_meta_name', $mydata);

// $mydata is a newly modified array that has been compared, edited, counted, then finally used as new value to be updated.

Leave a Comment