Kyon147 Kyon147 - 1 year ago 66
MySQL Question

Adding user ip to existing meta_value with single meta_id as array

I am currently getting the user IP on a slider change and sending it to the WP DB but I want to keep the DB smaller and have a single meta_id for the list of IPs.

My current code is sort of working but as it adds the new ip to the existing array something is causing it to turn into a multidimensional one and breaking it.

Here is my code.

$user_ip = $_POST['ip'];
$user_score = $_POST['sliderValue'];
$postID = $_POST['post_id'];

$currentIPs = maybe_unserialize(get_post_meta( $postID, 'user_ip'));

$currentIPs[] = $user_ip;

if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {

update_post_meta($postID, 'user_ip', $currentIPs);

echo var_dump($currentIPs);


I have tried with add_post_meta and that works fine but it creates a new meta_id for each IP which would just make the database huge. For performance and space saving I was just one key and ID with all the values.

Answer Source

The function is programmed to create a new meta_id every time you use update_meta_data. However the workaround is that you can store the IPS within same meta_id by seperating IPS with commas.


 $currentIPs   =  maybe_unserialize(get_post_meta( $postID, 'user_ip'));
 $currentIPs[] = $user_ip;
 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
 update_post_meta($postID, 'user_ip', $currentIPs);


$currentIPs = $user_ip;
$userIp = get_post_meta($postID, 'user_ip',true);
 if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
if (empty($userIp)) {
   update_post_meta($postID, 'user_ip', $currentIPs);
} else {
   $newvalue = $currentIPs .','. $userIp;
   update_post_meta($postID, 'user_ip', $newvalue);

Later if you want these data in an array, you can use php's explode() function afterwards

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download