Search code examples
phpwordpressunset

How to delete only user meta value (not key) from usermeta table in wordpress?


I store multiple image in media library and save its id in wp_usermeta table. my metakey is 'images' and meta value in like '279,280,281'. Now I get the image from table like this:

<?php $images = get_the_author_meta( 'images', $user->ID );
echo $images; //output is '279,280,281'.
 $images = explode(',',$images);
 foreach($images as $img) {
?>
      <img src="<?=wp_get_attachment_url( $img );?>" width="100" height="100" />
      <a href="<?php  echo get_edit_user_link( $user->ID ); ?>&image_id=<?= $img;?    >">Delete</a>
  <?php } ?>

Now, I wont to delete particular id from wp_usermeta table. So, please help me to solve it. I try this type of code for delete:

 if(isset($_REQUEST['image_id'])){
    $image_id = $_REQUEST['image_id'];
// delete_usermeta( $user->ID, $meta_value = $img );  
    if (($key = array_search($image_id, $images)) !== false) {
        unset($images[$key]);
    }   
    wp_delete_attachment($image_id);
    }

Solution

  • Well you can use get_user_meta to get to get all the image ids and then remove the one you want and update it. Something like this

    $ID_TO_REMOVE = 279;    
    $images = get_user_meta( $user_id, 'images', TRUE ); 
        $images = explode(',',$images);
        foreach($images as $image){
           if((int)$image != $ID_TO_REMOVE){
             $new_images .= $image.','; 
           }
        }
    
        update_user_meta($user_id, 'images', $new_images);
    

    I haven't tested this code, but it should be something like this.